Python · Lists
Lists as mutable sequences: append vs extend, slicing, sorting in place vs sorted(), and the aliasing trap.
A list is an ordered, mutable collection, and it can hold items of different types. The operations I worked through today:
append(x)adds one item.extend(iterable)adds every item from another iterable.insert(i, x),pop(i)andremove(x)insert or delete items.sort()sorts in place and returnsNone.sorted(lst)returns a new list and leaves the original alone.key=sorts by a computed value, for examplekey=len.
The biggest trap is aliasing. b = a does not copy the list. It gives the same list a second name, so changing b also changes a. Use a.copy() or a[:] to get a real copy (a shallow one).
a = [3, 1, 2]
a.append(4)
a.extend([0, 9])
print(a)
print(sorted(a), a) # sorted() leaves a alone
print(a.sort(), a) # sort() returns None, changes a
b = a # alias
c = a.copy() # copy
b.append(100)
print("a:", a)
print("c:", c)
words = ["numpy", "c++", "python", "ai"]
print(sorted(words, key=len))
print(sorted(words, key=len, reverse=True))
Output:
[3, 1, 2, 4, 0, 9]
[0, 1, 2, 3, 4, 9] [3, 1, 2, 4, 0, 9]
None [0, 1, 2, 3, 4, 9]
a: [0, 1, 2, 3, 4, 9, 100]
c: [0, 1, 2, 3, 4, 9]
['ai', 'c++', 'numpy', 'python']
['python', 'numpy', 'c++', 'ai']Sources
- Data Structures: more on lists — Python Software Foundation
- Mutable sequence types — Python Software Foundation
- Sorting Techniques — Python Software Foundation