at least 100 different operations topic is "List operation in python from basic to very…
- User
at least 100 different operations
topic is "List operation in python from basic to very advanced"
- Assistant
at least 100 different operations
topic is "List operation in python from basic to very advanced"
Certainly! Python lists are versatile and powerful data structures that support a wide range of operations, from basic manipulation to very advanced techniques. Below is a comprehensive list of 100 different list operations in Python, categorized from basic to advanced levels.
Create an Empty List
my_list = []
Create a List with Initial Elements
my_list = [1, 2, 3]
Create a List Using the list() Constructor
my_list = list((1, 2, 3))
Create a List with Repeated Elements
my_list = [0] * 5 # [0, 0, 0, 0, 0]
Create a List from a String
my_list = list("hello") # ['h', 'e', 'l', 'l', 'o']
Create a List Using List Comprehension
my_list = [x for x in range(5)] # [0, 1, 2, 3, 4]
Create a Nested List
my_list = [[1, 2], [3, 4]]
Create a List from Another List (Copy)
original = [1, 2, 3]
copy = original.copy()
Create a List from a Generator
my_list = list(x for x in range(5))
Create a List with Mixed Data Types
my_list = [1, "two", 3.0, True]
Access an Element by Index
element = my_list[0]
Access the Last Element
last = my_list[-1]
Access a Slice of the List
sub_list = my_list[1:3]
Access Every Nth Element
every_second = my_list[::2]
Access Elements with Negative Indices
second_last = my_list[-2]
Access Multiple Indices Using List Comprehension
indices = [0, 2]
elements = [my_list[i] for i in indices]
Access Elements Using a Loop
for item in my_list:
print(item)
Access Elements Using enumerate
for index, item in enumerate(my_list):
print(index, item)
Add an Element to the End (append)
my_list.append(4)
Insert an Element at a Specific Position (insert)
my_list.insert(1, 'a')
Extend a List with Another List (extend)
my_list.extend([5, 6])
Remove an Element by Value (remove)
my_list.remove('a')
Remove an Element by Index (del)
del my_list[0]
Pop an Element (pop)
last = my_list.pop()
Clear All Elements (clear)
my_list.clear()
Replace Elements via Slicing
my_list[1:3] = ['x', 'y']
Reverse the List (reverse)
my_list.reverse()
Sort the List (sort)
my_list.sort()
Sort the List in Reverse Order
my_list.sort(reverse=True)
Change an Element's Value Directly
my_list[2] = 'new'
Basic List Comprehension
squares = [x**2 for x in range(10)]
List Comprehension with Condition
evens = [x for x in range(10) if x % 2 == 0]
Nested List Comprehension
matrix = [[x for x in range(3)] for _ in range(3)]
List Comprehension with Multiple Iterables
combinations = [(x, y) for x in range(3) for y in range(3)]
List Comprehension with Function Calls
lengths = [len(s) for s in ["hello", "world"]]
Using if-else in List Comprehension
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
Generator Expression Inside list()
my_list = list(x**2 for x in range(5))
Flatten a Nested List
flat = [item for sublist in matrix for item in sublist]
List Comprehension with Exception Handling
safe_ints = [int(x) if x.isdigit() else 0 for x in ['1', 'a', '3']]
List Comprehension with Enumerate
indexed = [(i, x) for i, x in enumerate(['a', 'b', 'c'])]
Iterate Over List with a For Loop
for item in my_list:
print(item)
Iterate with Index Using range
for i in range(len(my_list)):
print(my_list[i])
Iterate with enumerate
for index, item in enumerate(my_list):
print(index, item)
Iterate Backwards Using reversed
for item in reversed(my_list):
print(item)
Iterate with Condition
for item in my_list:
if item > 0:
print(item)
Iterate and Modify Elements
for i in range(len(my_list)):
my_list[i] *= 2
Iterate Using map
doubled = list(map(lambda x: x * 2, my_list))
Iterate Using filter
positives = list(filter(lambda x: x > 0, my_list))
Check if an Element Exists (in)
exists = 3 in my_list
Find the Index of an Element (index)
idx = my_list.index(2)
Count Occurrences of an Element (count)
cnt = my_list.count(2)
Find All Indices of an Element
indices = [i for i, x in enumerate(my_list) if x == 2]
Find the First Matching Element
first = next((x for x in my_list if x > 0), None)
Find the Last Matching Element
last = next((x for x in reversed(my_list) if x > 0), None)
Map Function to List
squared = list(map(lambda x: x**2, my_list))
Filter Function on List
evens = list(filter(lambda x: x % 2 == 0, my_list))
Reduce Function on List
from functools import reduce
total = reduce(lambda x, y: x + y, my_list)
Sum of List Elements (sum)
total = sum(my_list)
Product of List Elements
from math import prod
product = prod(my_list)
Minimum and Maximum (min, max)
smallest = min(my_list)
largest = max(my_list)
Join List of Strings (join)
joined = ''.join(my_list) # Assuming all elements are strings
Convert List to Tuple
my_tuple = tuple(my_list)
Sort with a Custom Key
my_list.sort(key=lambda x: x.lower())
Sort with Multiple Criteria
my_list.sort(key=lambda x: (x[1], x[0]))
Stable Sort
my_list.sort(key=lambda x: x) # Python's sort is stable
Sort a Copy of the List (sorted)
sorted_list = sorted(my_list)
Sort in Place with reverse Parameter
my_list.sort(reverse=True)
Custom Sorting with Objects
my_list.sort(key=lambda obj: obj.attribute)
Slice from Start to Index
subset = my_list[:3]
Slice from Index to End
subset = my_list[2:]
Slice with Step
subset = my_list[::2]
Negative Slicing
subset = my_list[-3:-1]
Assign to a Slice
my_list[1:3] = ['a', 'b']
Delete a Slice
del my_list[2:4]
List Flattening with itertools.chain
import itertools
flattened = list(itertools.chain.from_iterable(my_list))
List Partitioning
from itertools import tee
a, b = tee(my_list, 2)
List Zipping
zipped = list(zip([1, 2], ['a', 'b']))
Unzip a List
zipped = [(1, 'a'), (2, 'b')]
numbers, letters = zip(*zipped)
List Copy (Shallow)
shallow_copy = my_list.copy()
List Deep Copy
import copy
deep_copy = copy.deepcopy(my_list)
List Multiplication and Repetition
repeated = my_list * 3
Check if List is Empty
is_empty = not my_list
Convert List of Lists to List of Tuples
list_of_tuples = [tuple(sublist) for sublist in my_list]
Rotate a List
from collections import deque
d = deque(my_list)
d.rotate(2)
rotated = list(d)
Find Unique Elements
unique = list(set(my_list))
List Intersection, Union, Difference
Compare Two Lists for Equality
are_equal = my_list == other_list
Check if One List is a Sublist of Another
def is_sublist(small, large):
return any(small == large[i:i+len(small)] for i in range(len(large)-len(small)+1))
Find Common Elements Between Two Lists
common = list(set(my_list).intersection(other_list))
Check if All Elements Meet a Condition (all)
all_positive = all(x > 0 for x in my_list)
Convert List to Set
my_set = set(my_list)
Convert List to Dictionary (with Index)
my_dict = {i: my_list[i] for i in range(len(my_list))}
Convert List of Tuples to Dictionary
list_of_tuples = [(1, 'a'), (2, 'b')]
my_dict = dict(list_of_tuples)
Integrate with NumPy Arrays
import numpy as np
array = np.array(my_list)
Using enumerate to Get Index and Value
for index, value in enumerate(my_list):
print(index, value)
Using any to Check for Any True Element
has_positive = any(x > 0 for x in my_list)
Using all to Check if All Elements are True
all_true = all(my_list)
Using len to Get List Length
length = len(my_list)
Using copy Method for Shallow Copy
copied_list = my_list.copy()
Using sorted to Get a Sorted List Without Modifying Original
sorted_list = sorted(my_list)
Using List Comprehensions for Faster Execution
squares = [x**2 for x in range(1000)]
Avoiding .append() in Loops by Using List Comprehension
my_list = [func(x) for x in iterable]
Preallocating List Size with Multiplication
my_list = [None] * 1000
Using deque for Efficient Inserts and Deletes
from collections import deque
d = deque(my_list)
d.appendleft(0)
Using Built-in Functions for Performance
total = sum(my_list)
Leveraging map and filter for Performance
mapped = list(map(func, my_list))
filtered = list(filter(lambda x: x > 0, my_list))
Using bisect for Binary Searches on Sorted Lists
import bisect
bisect.insort(my_list, 3)
Using heapq for Priority Queues
import heapq
heapq.heappush(my_list, 2)
Minimizing List Resizing Overhead
# Use list comprehension or preallocate to reduce append overhead
my_list = [0] * n
Using array Module for Homogeneous Data Types
import array
a = array.array('i', my_list)
Using List as a Stack
my_list.append(item)
top = my_list.pop()
Using List as a Queue with deque
from collections import deque
q = deque(my_list)
q.append(item)
front = q.popleft()
List Comprehensions with Multiple Conditions
filtered = [x for x in my_list if x > 0 and x % 2 == 0]
Using itertools for Advanced List Operations
import itertools
combinations = list(itertools.combinations(my_list, 2))
Using zip_longest to Handle Uneven Lists
from itertools import zip_longest
zipped = list(zip_longest(my_list1, my_list2, fillvalue=None))
List Indexing with Boolean Masks
import numpy as np
array = np.array(my_list)
filtered = array[array > 0]
Using functools.partial with List Operations
from functools import partial
add_five = partial(map, lambda x: x + 5)
new_list = list(add_five(my_list))
Using dataclasses with Lists
from dataclasses import dataclass
@dataclass
class Item:
value: int
my_list = [Item(x) for x in range(5)]
Implementing List Deduplication While Preserving Order
These 120 operations cover a broad spectrum of list manipulations in Python, from foundational techniques to sophisticated methods leveraging Python’s extensive standard library and third-party modules. Mastery of these operations will enable you to handle most list-related tasks efficiently and elegantly in your Python projects.
Not yet included in a published release.
list1 = [1, 2, 3]
list2 = [2, 3, 4]
intersection = list(set(list1) & set(list2))
union = list(set(list1) | set(list2))
difference = list(set(list1) - set(list2))
seen = set()
deduped = [x for x in my_list if not (x in seen or seen.add(x))]
Using List Factories for Dynamic List Creation
def create_list(n, value=0):
return [value for _ in range(n)]
my_list = create_list(10)