List Operations

Complete reference for Python list methods and operations. Lists are mutable, ordered sequences that can contain items of different types and provide extensive functionality for data manipulation and storage.

List Creation and Basic Operations

OperationSyntaxExampleResultDescription
Empty List[] or list()my_list = [][]Create empty list
List Literal[item1, item2, ...][1, 2, 3][1, 2, 3]Create list with items
List from Iterablelist(iterable)list("abc")['a', 'b', 'c']Convert iterable to list
List Comprehension[expr for item in iterable][x*2 for x in range(3)][0, 2, 4]Create list with expression
Repetition[item] * n[0] * 3[0, 0, 0]Repeat item n times
Concatenationlist1 + list2[1, 2] + [3, 4][1, 2, 3, 4]Join lists together
Lengthlen(list)len([1, 2, 3])3Get number of items
Membershipitem in list2 in [1, 2, 3]TrueCheck if item exists
Indexinglist[i][1, 2, 3][1]2Access item at index
Slicinglist[start:end:step][1, 2, 3, 4][1:3][2, 3]Extract sublists

Adding Elements Methods

MethodPurposeExampleResultDescription
append()Add single item to endlst.append(4)Modifies lstAdds item to end of list
insert()Insert item at indexlst.insert(1, 'new')Modifies lstInserts item at specified position
extend()Add multiple itemslst.extend([4, 5])Modifies lstAdds all items from iterable

Removing Elements Methods

MethodPurposeExampleResultDescription
remove()Remove first occurrencelst.remove(2)Modifies lstRemoves first matching item
pop()Remove and return itemlst.pop() or lst.pop(1)Returns removed itemRemoves from end or at index
clear()Remove all itemslst.clear()[]Empties the list
delDelete item(s)del lst[1] or del lst[1:3]Modifies lstDeletes item(s) at index/slice

Searching and Counting Methods

MethodPurposeExampleResultDescription
index()Find item indexlst.index(item)IntegerReturns index of first occurrence
count()Count occurrenceslst.count(item)IntegerReturns number of occurrences

Sorting and Reversing Methods

MethodPurposeExampleResultDescription
sort()Sort in placelst.sort()Modifies lstSorts list in ascending order
sort()Sort with keylst.sort(key=len)Modifies lstSorts using custom key function
sort()Sort descendinglst.sort(reverse=True)Modifies lstSorts in descending order
reverse()Reverse in placelst.reverse()Modifies lstReverses order of items
sorted()Return sorted copysorted(lst)New listReturns new sorted list
reversed()Return reversed iteratorlist(reversed(lst))New listReturns new reversed list

List Copying Methods

MethodPurposeExampleResultDescription
copy()Shallow copynew_list = lst.copy()New listCreates shallow copy
list()Copy constructornew_list = list(lst)New listCreates shallow copy
:Slice copynew_list = lst[:]New listCreates shallow copy

Advanced List Operations

List Comprehensions

TypeSyntaxExampleResultDescription
Basic[expr for item in iterable][x**2 for x in range(5)][0, 1, 4, 9, 16]Apply expression to each item
With Condition[expr for item in iterable if condition][x for x in range(10) if x % 2 == 0][0, 2, 4, 6, 8]Filter items with condition
Nested[expr for item in iterable for subitem in item][x for sublist in [[1,2],[3,4]] for x in sublist][1, 2, 3, 4]Flatten nested structures
Multiple Variables[expr for x, y in iterable][x+y for x, y in [(1,2), (3,4)]][3, 7]Unpack tuples in iteration

List Slicing Operations

OperationSyntaxExampleResultDescription
Basic Slicelst[start:end][1,2,3,4,5][1:4][2, 3, 4]Extract elements from start to end-1
Step Slicelst[start:end:step][1,2,3,4,5][::2][1, 3, 5]Extract every nth element
Negative Indiceslst[-n:][1,2,3,4,5][-2:][4, 5]Count from end
Reverse Slicelst[::-1][1,2,3,4,5][::-1][5, 4, 3, 2, 1]Reverse the list
Slice Assignmentlst[start:end] = iterablelst[1:3] = [10, 20]Modifies lstReplace slice with new items

Performance Considerations

Time Complexity

OperationTime ComplexityNotes
AppendO(1) amortizedUsually constant, occasional resize
Prepend (insert at 0)O(n)Must shift all elements
Insert at indexO(n)Must shift elements after index
Delete at endO(1)Pop from end is constant
Delete at indexO(n)Must shift elements after index
Search (in/index)O(n)Linear search through list
SliceO(k)Where k is slice length
SortO(n log n)Timsort algorithm

Performance Tips

# Efficient list building
# Bad: repeated concatenation
result = []
for i in range(1000):
    result = result + [i]  # O(n²) total time

# Good: use append
result = []
for i in range(1000):
    result.append(i)       # O(n) total time

# Good: use list comprehension
result = [i for i in range(1000)]  # Often fastest

# Efficient deletion
# Bad: removing from front
while lst:
    lst.pop(0)  # O(n²) total time

# Good: removing from back
while lst:
    lst.pop()   # O(n) total time

# Good: use collections.deque for frequent front operations
from collections import deque
dq = deque(lst)
while dq:
    dq.popleft()  # O(1) per operation

Best Practices

  • Use list comprehensions: Generally faster and more readable than loops
  • Avoid repeated concatenation: Use append() or extend() instead
  • Be careful with mutable defaults: Don't use def func(lst=[]):
  • Use enumerate(): Instead of manual indexing: for i, item in enumerate(lst)
  • Consider deque: For frequent insertions/deletions at both ends
  • Use appropriate data structures: Set for membership testing, dict for key-value pairs
  • Mind memory usage: Large lists can consume significant memory

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent