π Pythonπ
Day 8
Lists in Python
Create, index, slice and mutate lists. Common list methods and pitfalls.
π―
Learning objectives
- βCreate and modify lists
- βMaster slicing syntax lst[a:b:c]
- βKnow the difference between list methods that mutate vs return new
π‘ Key points
- Lists are ordered, mutable, allow duplicates, can hold mixed types.
- Zero-indexed. Negative indices count from the end: lst[-1] is last.
- Slicing: lst[start:stop:step] β stop is exclusive.
- .append() mutates in place and returns None. Don't do `lst = lst.append(x)`.
π» Code examples(4)
#1Create and access
pythonnums = [10, 20, 30, 40, 50]
print(nums[0]) # 10
print(nums[-1]) # 50
print(len(nums)) # 5
nums[2] = 99 # mutate in place
print(nums) # [10, 20, 99, 40, 50]
Negative indexing avoids `len(lst) - 1`. Mutation by index is instant.
#2Slicing
pythons = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(s[2:5]) # [2, 3, 4]
print(s[:3]) # [0, 1, 2]
print(s[7:]) # [7, 8, 9]
print(s[::2]) # [0, 2, 4, 6, 8]
print(s[::-1]) # reversed
Slices always return a NEW list. s[::-1] is the idiomatic reverse.
#3Common methods
pythonlst = [3, 1, 4, 1, 5]
lst.append(9) # [3, 1, 4, 1, 5, 9]
lst.insert(0, 100) # [100, 3, 1, 4, 1, 5, 9]
lst.remove(1) # removes FIRST 1
lst.pop() # removes + returns last
lst.sort() # in place
sorted(lst) # returns new sorted list
lst.reverse() # in place
sort/reverse mutate. sorted()/reversed() return new. Choose based on whether you need the original.
#4List concatenation vs extend
pythona = [1, 2]
b = [3, 4]
c = a + b # new list [1, 2, 3, 4]
a.extend(b) # a is now [1, 2, 3, 4]
a.append(b) # a is now [1, 2, 3, 4, [3, 4]] β nested!
append(list) puts the whole list as one element. extend(list) unpacks it. Different results.
π― Practice
Q1. Reverse a list without changing the original.+
reversed_lst = lst[::-1] # or list(reversed(lst))
Q2. Get every 3rd element from a list of 100 numbers.+
nums[::3]
Q3. Sort a list of dicts by the 'age' key.+
sorted(people, key=lambda p: p['age'])
π Notes
List comprehensions
The Pythonic way to transform or filter:
nums = [1, 2, 3, 4, 5]
squares = [n * n for n in nums] # [1, 4, 9, 16, 25]
even_sq = [n * n for n in nums if n % 2 == 0]# [4, 16]
The mutable-default-argument trap
def add_item(x, bucket=[]): # β default reused across calls
bucket.append(x)
return bucket
Two calls in a row share the same list. Fix:
def add_item(x, bucket=None):
if bucket is None:
bucket = []
bucket.append(x)
return bucket