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
Operation | Syntax | Example | Result | Description |
---|---|---|---|---|
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 Iterable | list(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 |
Concatenation | list1 + list2 | [1, 2] + [3, 4] | [1, 2, 3, 4] | Join lists together |
Length | len(list) | len([1, 2, 3]) | 3 | Get number of items |
Membership | item in list | 2 in [1, 2, 3] | True | Check if item exists |
Indexing | list[i] | [1, 2, 3][1] | 2 | Access item at index |
Slicing | list[start:end:step] | [1, 2, 3, 4][1:3] | [2, 3] | Extract sublists |
Adding Elements Methods
Method | Purpose | Example | Result | Description |
---|---|---|---|---|
append() | Add single item to end | lst.append(4) | Modifies lst | Adds item to end of list |
insert() | Insert item at index | lst.insert(1, 'new') | Modifies lst | Inserts item at specified position |
extend() | Add multiple items | lst.extend([4, 5]) | Modifies lst | Adds all items from iterable |
Removing Elements Methods
Method | Purpose | Example | Result | Description |
---|---|---|---|---|
remove() | Remove first occurrence | lst.remove(2) | Modifies lst | Removes first matching item |
pop() | Remove and return item | lst.pop() or lst.pop(1) | Returns removed item | Removes from end or at index |
clear() | Remove all items | lst.clear() | [] | Empties the list |
del | Delete item(s) | del lst[1] or del lst[1:3] | Modifies lst | Deletes item(s) at index/slice |
Searching and Counting Methods
Method | Purpose | Example | Result | Description |
---|---|---|---|---|
index() | Find item index | lst.index(item) | Integer | Returns index of first occurrence |
count() | Count occurrences | lst.count(item) | Integer | Returns number of occurrences |
Sorting and Reversing Methods
Method | Purpose | Example | Result | Description |
---|---|---|---|---|
sort() | Sort in place | lst.sort() | Modifies lst | Sorts list in ascending order |
sort() | Sort with key | lst.sort(key=len) | Modifies lst | Sorts using custom key function |
sort() | Sort descending | lst.sort(reverse=True) | Modifies lst | Sorts in descending order |
reverse() | Reverse in place | lst.reverse() | Modifies lst | Reverses order of items |
sorted() | Return sorted copy | sorted(lst) | New list | Returns new sorted list |
reversed() | Return reversed iterator | list(reversed(lst)) | New list | Returns new reversed list |
List Copying Methods
Method | Purpose | Example | Result | Description |
---|---|---|---|---|
copy() | Shallow copy | new_list = lst.copy() | New list | Creates shallow copy |
list() | Copy constructor | new_list = list(lst) | New list | Creates shallow copy |
: | Slice copy | new_list = lst[:] | New list | Creates shallow copy |
Advanced List Operations
List Comprehensions
Type | Syntax | Example | Result | Description |
---|---|---|---|---|
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
Operation | Syntax | Example | Result | Description |
---|---|---|---|---|
Basic Slice | lst[start:end] | [1,2,3,4,5][1:4] | [2, 3, 4] | Extract elements from start to end-1 |
Step Slice | lst[start:end:step] | [1,2,3,4,5][::2] | [1, 3, 5] | Extract every nth element |
Negative Indices | lst[-n:] | [1,2,3,4,5][-2:] | [4, 5] | Count from end |
Reverse Slice | lst[::-1] | [1,2,3,4,5][::-1] | [5, 4, 3, 2, 1] | Reverse the list |
Slice Assignment | lst[start:end] = iterable | lst[1:3] = [10, 20] | Modifies lst | Replace slice with new items |
Performance Considerations
Time Complexity
Operation | Time Complexity | Notes |
---|---|---|
Append | O(1) amortized | Usually constant, occasional resize |
Prepend (insert at 0) | O(n) | Must shift all elements |
Insert at index | O(n) | Must shift elements after index |
Delete at end | O(1) | Pop from end is constant |
Delete at index | O(n) | Must shift elements after index |
Search (in/index) | O(n) | Linear search through list |
Slice | O(k) | Where k is slice length |
Sort | O(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?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.