Note append adds one item; extend adds each element from an iterable. Using append with a list nests it: [1].append([2,3]) gives [1, [2,3]].
add to listappend iteminsert at positionextend listpush to list
remove, pop, del, clear
syntax
list.remove(value)
list.pop(index)
del list[index]
example
items = ["a", "b", "c", "d", "e"]
items.remove("c")
print(items)
last = items.pop()
print(last, items)
del items[0]
print(items)
output
['a', 'b', 'd', 'e']
e ['a', 'b', 'd']
['b', 'd']
Note remove() deletes the first matching value (raises ValueError if missing). pop() removes by index and returns the value. del removes by index without returning.
Note .sort() modifies the list in place and returns None. sorted() returns a new list. Use key= for custom ordering logic.
sort listorder listreverse listcustom sortsort by key
List Comprehensions
syntax
[expression for item in iterable if condition]
example
prices = [10, 25, 50, 75, 100]
affordable = [p for p in prices if p <= 50]
print(affordable)
squares = [n ** 2for n in range(1, 6)]
print(squares)
output
[10, 25, 50]
[1, 4, 9, 16, 25]
Note Comprehensions are more Pythonic and faster than equivalent for-loop-with-append patterns. Keep them simple; if nesting gets deep, use a regular loop.
list comprehensionfilter listtransform listmap list
List Unpacking & Starred Expressions
syntax
a, b, *rest = some_list
example
coords = [10, 20, 30, 40, 50]
x, y, *remaining = coords
print(x, y, remaining)
first, *_, last = coords
print(first, last)
output
10 20 [30, 40, 50]
10 50
Note Use _ as a throwaway variable name for values you do not need. The starred variable always produces a list, even if empty.
unpack listdestructure listfirst and laststarred expressionrest operator
Useful List Operations
syntax
len() / in / enumerate() / zip()
example
items = ["pen", "notebook", "eraser"]
print(len(items))
print("pen"in items)
for idx, item in enumerate(items, start=1):
print(f"{idx}. {item}")
output
3
True
1. pen
2. notebook
3. eraser
Note enumerate() gives (index, value) pairs. Pass start= to begin counting from a number other than 0.
list lengthcheck if in listenumerate listloop with index