Lists and Dictionaries
Lists and Dictionaries
Lists
Ordered, mutable sequence. Create with [] or list().
pythonnums = [1, 2, 3] nums.append(4) nums[0] # 1 nums[-1] # 4 (last) len(nums) # 4
Slicing: nums[1:3] is from index 1 up to (not including) 3. List comprehensions:
pythonsquares = [x ** 2 for x in range(5)] # [0, 1, 4, 9, 16]
Dictionaries
Key-value pairs. Create with {} or dict().
pythonuser = {\"name\": \"Alice\", \"age\": 25} user[\"name\"] # Alice user.get(\"city\", \"Unknown\") # default if key missing user[\"city\"] = \"NYC\"
Iterate: for k, v in user.items(): or for k in user:.
Tuples and sets
- Tuples – immutable:
t = (1, 2). - Sets – unique, unordered:
s = {1, 2, 2}gives{1, 2}.