Problem: Want to store 100 students โ 100 variables? Solution: collections.
Lists
A list is an ordered sequence of elements stored under one name.
Creating lists
empty_list = []
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed = ["text", 42, True, 3.14]
Indexing
Indexes start at 0!
fruits = ["apple", "banana", "orange"]
# 0 1 2
print(fruits[0]) # apple
print(fruits[-1]) # orange (last)
print(fruits[-2]) # banana (second to last)
fruits[1] = "pear" # modify an element
print(len(fruits)) # 3
Slicing
Syntax: list[start:end:step]
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # [2, 3, 4]
print(numbers[:5]) # [0, 1, 2, 3, 4]
print(numbers[5:]) # [5, 6, 7, 8, 9]
print(numbers[::2]) # [0, 2, 4, 6, 8]
print(numbers[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print(numbers[-3:]) # [7, 8, 9]
Slices create a new list โ the original is not modified.
List Methods
fruits = ["apple", "banana"]
fruits.append("orange") # add to the end
fruits.insert(1, "pear") # insert at a position
fruits.remove("banana") # remove by value (first occurrence)
last = fruits.pop() # remove and return the last element
first = fruits.pop(0) # remove and return by index
fruits.clear() # clear the entire list
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort() # sort in place โ [1, 1, 2, 3, 4, 5, 9]
numbers.sort(reverse=True) # reverse sort
numbers.reverse() # reverse in place
print(numbers.count(1)) # 2 โ count occurrences
print(numbers.index(4)) # find index of element
list1 = [1, 2, 3]
list1.extend([4, 5, 6]) # add elements from another list
Membership test
if "banana" in fruits:
print("We have it!")
if "pear" not in fruits:
print("No pears")
Dictionaries
A dictionary is a collection of key-value pairs. Access by key, not by index.
Creating dictionaries
empty_dict = {}
student = {
"name": "Anna",
"age": 16,
"city": "Moscow",
"grade": 10
}
# Keys can be strings or numbers
scores = {1: 100, 2: 85, 3: 92}
Access, modify, add, remove
print(student["name"]) # Anna
print(student["age"]) # 16
student["age"] = 17 # modify
student["email"] = "a@mail.com" # add a new key
del student["email"] # remove key
age = student.pop("age") # remove and return value
Dictionary Methods
student = {"name": "Anna", "age": 16, "city": "Moscow"}
# get() โ safe lookup (no KeyError)
email = student.get("email", "No email") # "No email"
age = student.get("age", 0) # 16
# keys(), values(), items()
print(list(student.keys())) # ['name', 'age', 'city']
print(list(student.values())) # ['Anna', 16, 'Moscow']
# update() โ update multiple keys at once
student.update({"age": 17, "grade": 11})
# Check key membership
if "name" in student:
print("Name is present!")
student.clear() # clear the dictionary
Iteration
Over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# With index (enumerate):
for i, fruit in enumerate(fruits, 1):
print(f"{i}. {fruit}")
# 1. apple
# 2. banana
# 3. orange
Over a dictionary
student = {"name": "Anna", "age": 16, "city": "Moscow"}
for key in student: # keys only
print(key)
for value in student.values(): # values only
print(value)
for key, value in student.items(): # keys and values
print(f"{key}: {value}")
Practical Example: TODO List
tasks = []
# Adding tasks
tasks.append("Study")
tasks.append("Exercise")
tasks.append("Reading")
# Display
print("My tasks:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")
# Remove a task
tasks.remove("Exercise")
print(f"Remaining: {len(tasks)} tasks")
# Check
if "Study" in tasks:
print("Study is still pending!")
Common Mistakes
1. IndexError โ out of bounds:
fruits = ["apple", "banana"]
print(fruits[5]) # โ IndexError!
# Check length first: if len(fruits) > 5: ...
2. KeyError โ key not found:
student = {"name": "Anna"}
print(student["age"]) # โ KeyError!
# Use get(): student.get("age", 0)
3. Copying lists:
# โ This is a reference, not a copy:
list2 = list1
list2[0] = 999
print(list1) # [999, ...] โ changed!
# โ
An actual copy:
list2 = list1.copy() # or list1[:]
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!