Basic Looping Through a List
The most straightforward way to loop through a list in Python is using a for loop. This method is simple and intuitive.
Example 1:
# List declaration animals = ["cat", "dog", "rabbit"] # Loop through the list for animal in animals: print(animal)
Explanation:
The variable animal takes on each value from the animals list in turn, and print(animal) outputs each element during the loop’s iteration.
Accessing Indices and Elements
Sometimes, it’s useful to know the index of each element while looping through the list. You can use the enumerate() function to get both the index and the element.
Example 2:
# List declaration numbers = [10, 20, 30] # Loop with indices and elements for index, number in enumerate(numbers): print(f"Index {index}: {number}")
Explanation:
The enumerate() function returns an iterable of tuples (index, element). This allows you to access both the index and the element during each iteration.
Using Additional Variables
You might need additional variables to perform calculations or transformations during the loop.
Example 3:
# List declaration numbers = [1, 2, 3, 4, 5] # Initialize a variable for the sum total = 0 # Loop to calculate the sum of elements for number in numbers: total += number print(f"The sum of the numbers is: {total}")
Explanation:
The total variable accumulates the values from the numbers list. Each number is added to total during the loop.
Incorporating Conditions
You can include conditions inside your loop to filter or modify elements based on certain criteria.
Example 4:
# List declaration numbers = [1, 2, 3, 4, 5, 6] # Loop with condition for number in numbers: if number % 2 == 0: print(f"{number} is even") else: print(f"{number} is odd")
Explanation:
The condition if number % 2 == 0 checks if a number is even. Based on this condition, a message is printed for each element.
Modifying Elements In-Place
Sometimes, you may want to modify elements of the list directly. This can be achieved by accessing elements through their indices.
Example 5:
# List declaration fruits = ["apple", "banana", "cherry"] # Loop to modify elements for i in range(len(fruits)): fruits[i] = fruits[i].upper() print(fruits)
Explanation:
Using range(len(fruits)), you obtain indices of the list elements. These indices are used to modify the elements of the list in place, converting each fruit name to uppercase.
Nested Loops
When dealing with a list of lists, nested loops can be used to access each individual element.
Example 6:
# List of lists declaration matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Nested loop to access each element for row in matrix: for element in row: print(element, end=" ") print()
Explanation:
The outer loop iterates through each sub-list (row) in matrix, and the inner loop iterates through each element in each sub-list, printing them.
Summary
Looping through lists is a fundamental operation in Python that can be done in several ways:
- Basic Looping: Use a for loop to directly access each element.
- Accessing Indices and Elements: Use enumerate() to get both index and element.
- Using Additional Variables: Accumulate or transform data using extra variables.
- Incorporating Conditions: Apply conditions within the loop to filter or modify elements.
- Modifying Elements In-Place: Access elements by indices to modify them directly.
- Nested Loops: Use nested loops to handle lists of lists.