What are lists in Python and what are the most common list operations?
A list is a mutable, ordered sequence that can hold items of any type. Lists are the most versatile data structure in Python.
Creation: [], list(), list comprehension
Key operations:
- Add:
append(x),extend(iterable),insert(i, x),+(concatenation) - Remove:
remove(x),pop(i),del lst[i],clear() - Search:
index(x),count(x),x in lst - Sort:
sort(),sorted(),reverse() - Other:
copy(),len(), slicing
Internals: CPython lists are dynamic arrays (not linked lists). This means:
- Index access: O(1)
- Append: O(1) amortized
- Insert/delete at beginning: O(n)
- Search: O(n)
Create: [], list(), [x for x in iterable]
Add: append(x), extend(iter), insert(i, x)
Remove: remove(x), pop(i), del lst[i]
Search: index(x), count(x), x in lst
Sort: sort() in-place, sorted() new list
Performance:
Index: O(1), Append: O(1), Insert/Delete at 0: O(n), Search: O(n)
# Creation
lst = [1, 2, 3]
lst2 = list(range(5)) # [0, 1, 2, 3, 4]
lst3 = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
# Adding elements
lst = [1, 2, 3]
lst.append(4) # [1, 2, 3, 4]
lst.extend([5, 6]) # [1, 2, 3, 4, 5, 6]
lst.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6]
lst += [7, 8] # [0, 1, 2, 3, 4, 5, 6, 7, 8]
# Removing elements
lst = [1, 2, 3, 2, 4]
lst.remove(2) # [1, 3, 2, 4] (removes first occurrence)
last = lst.pop() # last=4, lst=[1, 3, 2]
first = lst.pop(0) # first=1, lst=[3, 2]
lst = [1, 2, 3, 4, 5]
del lst[1] # [1, 3, 4, 5]
del lst[1:3] # [1, 5]
# Searching
lst = [10, 20, 30, 20, 40]
print(lst.index(20)) # 1 (first occurrence)
print(lst.count(20)) # 2
print(20 in lst) # True
print(50 in lst) # False
# Sorting
lst = [3, 1, 4, 1, 5, 9]
lst.sort() # [1, 1, 3, 4, 5, 9] in-place
lst.sort(reverse=True) # [9, 5, 4, 3, 1, 1]
lst = [3, 1, 4]
new = sorted(lst) # new=[1, 3, 4], lst unchanged
# Reversing
lst = [1, 2, 3]
lst.reverse() # [3, 2, 1] in-place
new = list(reversed(lst)) # creates new list
# Slicing (creates new list)
lst = [0, 1, 2, 3, 4]
print(lst[1:3]) # [1, 2]
print(lst[::-1]) # [4, 3, 2, 1, 0]
# Copying
import copy
lst = [[1, 2], [3, 4]]
shallow = lst.copy() # or lst[:] or list(lst)
deep = copy.deepcopy(lst) # for nested structures
# Nested lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][2]) # 6
- •Lists are mutable, ordered, and can hold mixed types
- •append() adds one item, extend() adds from iterable
- •sort() modifies in-place (returns None), sorted() returns new list
- •Lists are dynamic arrays: O(1) index, O(1) append, O(n) insert at 0
- •Slicing always creates a new list
- •append([4,5]) adds a single list element, extend([4,5]) adds two elements
- •sort() returns None -- do not assign: sorted_lst = lst.sort() is a bug
- •remove() raises ValueError if element not found
- •[[]] * 3 creates three references to the SAME inner list