Python Lists
A list is an ordered, mutable sequence. Probably the collection you'll use most.
Create & access
PYTHON
fruits = ['apple', 'banana', 'cherry'] fruits[0] # 'apple' fruits[-1] # 'cherry' fruits[1:] # ['banana', 'cherry'] len(fruits) # 3
Mutate
| Method | What it does |
|---|---|
append(x) | Add to end. |
extend(iter) | Append every item. |
insert(i, x) | Insert at index. |
remove(x) | Remove first occurrence. |
pop(i=-1) | Remove and return item at i. |
clear() | Empty it. |
sort() / reverse() | In place. |
Iterate
PYTHON
for f in fruits:
print(f)
for i, f in enumerate(fruits, start=1):
print(i, f)
Comprehensions
PYTHON
nums = [1, 2, 3, 4, 5] squares = [n * n for n in nums] evens = [n for n in nums if n % 2 == 0]
Copy carefully
PYTHON
a = [1, 2, 3] b = a # same list — changes to one affect the other c = a.copy() # independent shallow copy d = a[:] # also shallow copy import copy e = copy.deepcopy(a) # for nested structures
Tip: Need a fixed-size, fixed-type buffer? Reach for
array.array or NumPy. Need O(1) appends from both ends? Use collections.deque.Example
Example
fruits = ['apple', 'banana', 'cherry']
fruits.append('date')
print(fruits[1]) # banana
for f in fruits:
print(f)
Try it Yourself »
Exercise
Add an item to the end of the list.
fruits.
('date')
Six letters.
Discussion
Loading…