List operations:
fruits = ["apple", "banana", "cherry"]
fruits.append("date") # add to end
fruits.insert(1, "avocado") # insert at index 1
fruits.remove("banana") # remove by value
popped = fruits.pop() # remove and return last item
print(len(fruits)) # 3
# List comprehension: concise way to build a list
squares = [x ** 2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
evens = [x for x in range(20) if x % 2 == 0]
# Slicing
print(fruits[1:3]) # elements at index 1 and 2
print(fruits[::-1]) # reversed
Dictionary operations:
person = {"name": "Alice", "age": 30, "city": "London"}
person["email"] = "[email protected]" # add / update
print(person.get("phone", "N/A")) # safe access with default
# Iterate
for key, value in person.items():
print(f"{key}: {value}")
# Check membership
print("age" in person) # True
del person["city"] # remove a key
# Dict comprehension
squares = {x: x**2 for x in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Use collections.defaultdict or dict.setdefault() when you need to handle missing keys gracefully without repeated if key in d checks.