Master Python’s four core containers — when to use each — and write concise comprehensions to build new collections from old ones.
Why: a list holds an ordered sequence of items that you can change — add, remove, or update. It is the workhorse container in Python.
nums = [3, 1, 2]
nums.append(4) # add to the end -> [3, 1, 2, 4]
nums[0] = 99 # change an item -> [99, 1, 2, 4]
nums.remove(1) # remove a value -> [99, 2, 4]
nums.sort() # sort in place -> [2, 4, 99]
print(len(nums)) # 3
print(2 in nums) # True (is 2 present?)Why: a tuple is like a list but cannot be changed after it is created. Use it for groups of values that belong together and should not change, like coordinates or a row of data.
point = (10, 20)
print(point[0]) # 10
x, y = point # "unpack" into two variables
print(x, y) # 10 20
# point[0] = 5 # ERROR: tuples can't be changedWhy: a set automatically throws away duplicates and is great for membership checks and removing repeats. It has no order, so you cannot index into it.
tags = {'python', 'web', 'python'}
print(tags) # {'python', 'web'} (duplicate dropped)
tags.add('api')
print('web' in tags) # True
# remove duplicates from a list in one step
unique = set([1, 1, 2, 3, 3]) # {1, 2, 3}Why: a dictionary maps keys to values, like a real dictionary maps words to definitions. Use it to look things up by name instead of by position.
user = {'name': 'Ada', 'age': 30}
print(user['name']) # 'Ada'
user['age'] = 31 # update a value
user['email'] = 'a@x.com' # add a new pair
# .get() avoids a crash if the key is missing
print(user.get('phone', 'none')) # 'none' (default)
for key, value in user.items():
print(key, value)Why: a comprehension builds a new list, set, or dict in a single readable line — replacing a loop that just appends. Read it as "give me EXPRESSION for each ITEM in COLLECTION".
nums = [1, 2, 3, 4, 5]
# square every number
squares = [n * n for n in nums] # [1, 4, 9, 16, 25]
print(squares)
# keep only the even ones (with a filter)
evens = [n for n in nums if n % 2 == 0] # [2, 4]
print(evens)
# dict comprehension: number -> its square
lookup = {n: n * n for n in nums} # {1: 1, 2: 4, ...}
print(lookup)