Practical Techniques and Examples
Now that you understand the basics of manually iterating over a Python list, let's explore some practical techniques and examples.
Filtering List Elements
You can use a for
loop to filter a list and create a new list containing only the elements that meet a certain condition.
numbers = [5, 10, 15, 20, 25, 30]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers) ## Output: [10, 20, 30]
In this example, we iterate over the numbers
list and add each even number to the even_numbers
list.
Modifying List Elements
You can also use a for
loop to modify the elements in a list.
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
fruits[i] = fruits[i].upper()
print(fruits) ## Output: ['APPLE', 'BANANA', 'CHERRY']
Here, we iterate over the indices of the fruits
list and convert each element to uppercase.
Nested Loops and List Comprehension
Nested loops can be used to iterate over lists of lists, which can be useful for processing multidimensional data.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=" ")
print()
This will output:
1 2 3
4 5 6
7 8 9
Alternatively, you can use a list comprehension to achieve the same result in a more concise way:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_matrix = [element for row in matrix for element in row]
print(flattened_matrix) ## Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
The list comprehension iterates over the rows and then the elements within each row to create a new flattened list.
These examples demonstrate how manual iteration over lists can be used to perform various operations and transformations on the data, making it a powerful technique in your Python programming toolkit.