Collections are data structures that can hold multiple items, while loops are used to iterate over these collections. In this section, we will explore lists and dictionaries as examples of collections, and we will learn how to use loops to work with them.

📝 Lists¶
Lists are a fundamental data structure in Python, allowing you to store multiple items in a single variable. Loops are used to iterate over these items, enabling you to perform operations on each element in the list.
🛠️ List Operations¶
🆕 Creating Lists¶
You can create a list by placing items inside square brackets [], separated by commas. Lists can contain items of different data types, including numbers, strings, and even other lists.
# Creating a list of integers
numbers = [1, 2, 3, 4, 5]
# Creating a list of strings
fruits = ["apple", "banana", "cherry"]
# Creating a mixed list
mixed = [1, "hello", 3.14, True]
# Creating a nested list
nested = [[1, 2], [3, 4], [5, 6]]You can check the type of a list using the type() function:
print(type([1, 2, 3]))  # Output: <class 'list'>📚 Accessing List Elements¶
# Accessing elements by index
first_number = numbers[0]   # 1
second_fruit = fruits[1]    # "banana"
third_item = mixed[2]       # 3.14
first_sublist = nested[0]   # [1, 2]
# Accessing the last element
last_fruit = fruits[-1]     # "cherry"
# Slicing a list
sublist = numbers[1:4]      # [2, 3, 4]✏️ Modifying Lists¶
numbers[0] = 10         # numbers is now [10, 2, 3, 4, 5]
fruits.append("date")   # fruits is now ["apple", "banana", "cherry", "date"]
mixed.remove(3.14)      # mixed is now [1, "hello", True]
nested[1][0] = 30       # nested is now [[1, 2], [30, 4], [5, 6]]✂️ Slicing Lists¶
You can extract a portion of a list using slicing. Slicing allows you to create a new list that contains a subset of the elements from the original list.
numbers = [1, 2, 3, 4, 5]
sublist = numbers[1:4]      # [2, 3, 4]Note that the starting index is inclusive, while the ending index is exclusive.
📏 Length of a List¶
You can find out how many items are in a list using the len() function.
fruits = ["apple", "banana", "cherry"]
length = len(fruits)  # 3🔒 Tuples¶
Tuples are similar to lists, but they are immutable, meaning their elements cannot be changed after creation. Tuples are defined using parentheses ().
# Creating a tuple
coordinates = (10, 20)
x = coordinates[0]
y = coordinates[1]
print(f"x: {x}, y: {y}")The output of the above code will be:
x: 10, y: 20You can check the type of a tuple using the type() function:
print(type((1, 2, 3)))  # Output: <class 'tuple'>Tuples are often used to represent fixed collections of items, such as coordinates or RGB color values.
In this course, we will primarily use lists, but it’s important to be aware of tuples as they are commonly used in Python programming.
🔁 Loops¶
Loops are used to execute a block of code repeatedly. In Python, there are two main types of loops: for loops and while loops.
➡️ For Loops¶
You can use for loops to iterate over the elements of a list. This allows you to perform operations on each item in the list.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
Here’s the output of the above code:
# Output:
apple
banana
cherryYou can also use loops to perform operations on each element in a list. For example, you can multiply each number in a list by 2.
numbers = [1, 2, 3, 4, 5]
for i in numbers:
    print(i * 2)Here’s the output of the above code:
# Output:
2
4
6
8
10🛞 For Loop Examples¶
🎯 Example: Counting Items in a List
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16fruits = ["Apple", "Banana", "Mango", "Orange", "Apple", "Grapes", "Mango", "Apple", "Banana", "Apple", "Orange", "Apple", "Mango", "Peach", "Apple", "Apple", "Banana", "Apple", "Apple", "Mango", "Orange", "Apple", "Apple", "Banana", "Apple", "Apple", "Grapes", "Apple", "Peach", "Apple"] num_apple = 0 # Counting the number of "Apple" in the list for fruit in fruits: if fruit == "Apple": num_apple += 1 print(f"You have {num_apple} apples.") # Output: You have 15 apples.
Program 1:Counting Items in a List
In Program 1 code above, we iterate through the list of fruits and increment the num_apple counter each time we encounter “Apple”. Finally, we print the total count of apples.
The += operator is a shorthand for incrementing a variable by a certain value. For example, num_apple += 1 is equivalent to num_apple = num_apple + 1. Each time we find “Apple” in the list, we increase the count by 1 using this shorthand increment operator.
🎯 Example: Summing Values in a List
1 2 3 4 5 6 7 8 9hours_worked = [8, 7, 9, 6, 8] total_hours = 0 # YOUR CODE BEGINS for v in hours_worked: total_hours += v # YOUR CODE ENDS print(f"Total hours worked: {total_hours}") # Output: Total hours worked: 38
Program 2:Summing Values in a List
In the Program 2 code above, we iterate through the list of hours worked and add each value to the total_hours variable. Finally, we print the total hours worked.
🎯 Example: Summing Odd Numbers
1 2 3 4 5 6 7 8 9 10nums = [1, 2, 3, 4, 5, 6, 7, 8] odd_sum = 0 # YOUR CODE BEGINS for num in nums: if num % 2 != 0: odd_sum += num # YOUR CODE ENDS print(f"Sum of odd numbers: {odd_sum}") # Output: Sum of odd numbers: 16
Program 3:Summing Odd Numbers in a List
In the Program 3 code above, we iterate through the list of numbers and check if each number is odd. If it is, we add it to the odd_sum variable. Finally, we print the total sum of odd numbers.
🎯 Example: Average of Even Numbers and Odd Numbers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24nums = [15, 8, 7, 5, 15, 72, -20, -66, 9, -4, -11, 21, 19] even_sum = 0 even_count = 0 odd_sum = 0 odd_count = 0 for n in nums: if n % 2 == 0: even_sum += n even_count += 1 else: odd_sum += n odd_count += 1 even_avg = even_sum / even_count odd_avg = odd_sum / odd_count print(f'Average of even numbers is {even_avg}') print(f'Average of odd numbers is {odd_avg}') # Output: # Average of even numbers is -2.0 # Average of odd numbers is 10.0
Program 4:Calculate Average of Even Numbers and Odd Numbers in a List
In the Program 4 code above, we iterate through the list of numbers and separate them into even and odd categories. We maintain separate sums and counts for both even and odd numbers. After the loop, we calculate the average for each category by dividing the sum by the count. Finally, we print the averages of even and odd numbers.
🔢 Looping with range()¶
The range() function generates a sequence of numbers, which is often used in for loops to iterate a specific number of times.
print(range(5))  # Output: range(0, 5)The range object above represents a sequence of numbers from 0 to 4 (5 is exclusive). You can convert it to a list to see the actual numbers:
for i in range(5):
    print(i)Here’s the output of the above code:
# Output:
0
1
2
3
4We can use the range() function to dynamically generate indices for accessing elements in a list.
majors = ["Accounting", "Finance", "Marketing"]
for i in range(len(majors)):
    print(majors[i])
# Output:
# Accounting
# Finance
# MarketingThis code iterates through the indices of the majors list and prints each major by accessing it using its index. Note that len(majors) returns the length of the list, which is 3 in this case, so range(len(majors)) generates the sequence 0, 1, 2. This code will work for lists of any length, because it dynamically calculates the length of the list.
🎯 Example: Comparing Two Lists Using Positional Indices
Imagine you run a small contest where people predict the winners of upcoming games.
You are given two lists: predicted_winners and actual_winners. Each list contains the predicted and actual winners of a series of games, respectively.
Your task is to compare their values at each index using a for loop, and count the number of predictions that were correct. A prediction is considered correct if the value at a given index in the predicted_winners list matches the value at the same index in the actual_winners list. Store the count of correct predictions in a variable called num_correct.
You can assume that both lists have the same length (i.e., the same number of elements).
1 2 3 4 5 6 7 8 9 10predicted_winners = ["Illinois", "Purdue", "Rutgers", "Washington"] actual_winners = ["Illinois", "Indiana", "Maryland", "Washington"] num_correct = 0 for i in range(len(predicted_winners)): if predicted_winners[i] == actual_winners[i]: num_correct += 1 print(f"Number of correct predictions: {num_correct}") # Output: Number of correct predictions: 2
Program 5:Comparing Two Lists Using Positional Indices
In Program 5 code above, we iterate through the lists using their indices and compare the values at each index. If the values match, we increment the num_correct counter. Finally, we print the total number of correct predictions.
The += operator is a shorthand for incrementing a variable by a certain value. For example, num_correct += 1 is equivalent to num_correct = num_correct + 1. Each time we find a correct prediction, we increase the count by 1 using this shorthand increment operator.
♻️ Nested Loops¶
You can also use nested loops, which are loops inside other loops. This is useful for working with multi-dimensional lists.
nested = [[1, 2], [3, 4], [5, 6]]
for sublist in nested:
    for item in sublist:
        print(item)Here’s the output of the above code:
# Output:
1
2
3
4
5
6🔄 While Loops¶
A while loop continues to execute as long as a specified condition is True. Be careful to ensure that the condition will eventually become False, or you may create an infinite loop.
count = 0
while count < 5:
    print(count)
    count += 1  # Increment count to avoid infinite loopHere’s the output of the above code:
# Output:
0
1
2
3
4📖 Dictionaries¶
Dictionaries are another important collection type in Python. They store data in key-value pairs, allowing you to quickly retrieve values based on their associated keys.
🛠️ Dictionary Operations¶
🆕 Creating Dictionaries¶
You can create a dictionary by placing key-value pairs inside curly braces {}, separated by commas. Each key is separated from its value by a colon :.
person = {
    "name": "John",
    "age": 30,
    "city": "Champaign"
}You can check the type of a dictionary using the type() function:
print(type({"key": "value"}))  # Output: <class 'dict'>🎯 Accessing Dictionary Values¶
To access a value in a dictionary, you use its key inside square brackets [].
name = person["name"]  # "John"
age = person["age"]    # 30
city = person["city"]  # "Champaign"
print(name) # Output: John
print(age)  # Output: 30
print(city) # Output: Champaign✏️ Modifying Dictionaries¶
You can add new key-value pairs or update existing ones by assigning a value to a key.
person["email"] = "john@example.com"  # Add new key-value pair
person["age"] = 31                    # Update existing value🧩 Nested Dictionaries¶
Dictionaries can also contain other dictionaries, allowing you to create complex data structures.
people = {
    "person1": {
        "name": "John",
        "age": 30
    },
    "person2": {
        "name": "Jane",
        "age": 25
    }
}🔎 Looping Through Dictionaries¶
You can use a for loop to iterate over the keys in a dictionary. You can then use these keys to access the corresponding values.
for person_key in people:
    person = people[person_key]
    print(f"{person['name']} is {person['age']} years old.")Here’s the output of the above code:
# Output:
John is 30 years old.
Jane is 25 years old.You can also loop through both keys and values using the .items() method.
for person_key, person in people.items():
    print(f"{person_key}: {person['name']} is {person['age']} years old.")Here’s the output of the above code:
# Output:
person1: John is 30 years old.
person2: Jane is 25 years old.🥣 Mixing Collections and Loops¶
You can combine lists and dictionaries to create more complex data structures. For example, you can have a list of dictionaries, where each dictionary represents a person.
people = [
    {
        "name": "John",
        "age": 30
    },
    {
        "name": "Jane",
        "age": 25
    }
]
for person in people:
    print(f"{person['name']} is {person['age']} years old.")Here’s the output of the above code:
# Output:
John is 30 years old.
Jane is 25 years old.You can also have a dictionary of lists, where each key represents a category and the value is a list of items in that category.
fruits = {
    "citrus": ["orange", "lemon", "lime"],
    "berries": ["strawberry", "blueberry", "raspberry"]
}
for category, fruit_list in fruits.items():
    print(f"{category.capitalize()}:")
    for fruit in fruit_list:
        print(f" - {fruit}")Here’s the output of the above code:
# Output:
Citrus:
 - orange
 - lemon
 - lime
Berries:
 - strawberry
 - blueberry
 - raspberry🎯 Example: Calculating Total Salary of Engineering Employees
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35employees = [ { "name": "Alice", "department": "Engineering", "salary": 95000 }, { "name": "Bob", "department": "Marketing", "salary": 72000 }, { "name": "Charlie", "department": "Engineering", "salary": 105000 }, { "name": "Diana", "department": "HR", "salary": 68000 }, { "name": "Ethan", "department": "Engineering", "salary": 99000 } ] engineering_total_salary = 0 for e in employees: if e["department"] == "Engineering": engineering_total_salary += e["salary"] print(f"Engineering employees' total salary is {engineering_total_salary}!") # Output: Engineering employees' total salary is 299000!
Program 6:Calculate Total Salary of Engineering Employees
In the Program 6 code above, we iterate through the list of employees and check if each employee belongs to the “Engineering” department. If they do, we add their salary to the engineering_total_salary variable. Finally, we print the total salary of all engineering employees.
The if statement inside the loop allows us to filter the employees based on their department, ensuring that we only sum the salaries of those in the “Engineering” department. It is indented to be part of the loop, meaning it is executed for each employee in the list. It checks the condition for each employee and only adds their salary to the total if they meet the criteria.