Processing Lists
Lists are one of the most commonly used data structures in Python, and loops allow us to process them efficiently. In this lesson, we will explore different ways to process lists using for loops. We will learn how to iterate through lists, apply operations to each element, and perform common list manipulations.
Iterating Through Lists
A for loop can be used to process each element in a list one by one. This is particularly useful when you need to apply the same operation to every item in a list.
Example: Printing each item in a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Explanation
-
The loop iterates over fruits, assigning each element to fruit in each iteration.
-
The print() function prints each fruit on a new line.
-
Transforming Lists Using Loops
-
We can modify each item in a list and store the results in a new list using loops.
Example: Converting a list of names to uppercase
names = ["alice", "bob", "charlie"]
uppercase_names = []
for name in names:
uppercase_names.append(name.upper())
print(uppercase_names) # Output: ['ALICE', 'BOB', 'CHARLIE']
Explanation
-
We start with a list of lowercase names.
-
We create an empty list uppercase_names.
-
Using a for loop, we process each name and append the uppercase version to uppercase_names.
-
Using range() to Iterate Over List Indices
Sometimes, we need access to both the index and the value of each element in a list. The range(len(list))
pattern helps with this.
Example: Printing index and value
colors = ["red", "green", "blue"]
for i in range(len(colors)):
print(f"Index {i}: {colors[i]}")
Explanation
-
range(len(colors))
generates indices from0
tolen(colors) - 1
. -
We use
colors[i]
to access each element by its index.
List Comprehension (Alternative to Loops)
Python provides a concise way to process lists using list comprehensions. This method is often more readable and efficient.
Example: Squaring numbers using list comprehension
numbers = [1, 2, 3, 4]
squared_numbers = [num ** 2 for num in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16]
Explanation
-
Instead of using a for loop, we use a single line to generate a new list.
-
num ** 2
for num in numbers squares each number in numbers.
Exercise: Try It Yourself!
Task 1: Double the Values
Write a program that doubles each number in the given list and prints the new list.
numbers = [3, 6, 9, 12]
### Your code here
Task 2: Extract First Letters
Given a list of words, create a new list containing only the first letter of each word.
words = ["Python", "Loops", "Lists", "Fun"]
### Your code here
Conclusion
Processing lists with loops allows us to perform powerful operations efficiently. Whether iterating through a list, modifying elements, or using list comprehensions, these techniques are essential for working with collections of data. Next, we will explore how nested lists work and how to process them effectively.