6.1 for
Loop
In Python, looping through list elements is often done using the
for
loop. It's one of the most common methods for iterating over a list,
allowing you to execute a block of code for each item in the list.
For Loop Basics
The for
loop in Python goes through each element in the list, temporarily
assigning the current element's value to the variable specified after the
for
keyword. Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
You can iterate through a list in reverse order using slices:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits[::-1]:
print(fruit)
6.2 for
Loop with Indexes
Besides iterating through a list with a classic for
, you can loop
through it using a for
loop in combination with the range()
function. This
allows you to work not only with the elements themselves but also with their positions,
which is necessary for more complex data manipulations.
Indexed Iteration Basics
To iterate through a list with access to each element's index, you can use the following approach:
my_list = ['a', 'b', 'c', 'd']
for i in range(len(my_list)):
print(f'Index: {i}, Element: {my_list[i]}')
Advantages of Using Indexes
Using indexes in loops allows not only access to each element, but also to modify list elements in place. This is particularly useful when you need to alter the list during iteration.
Example:
my_list = ['a', 'b', 'c', 'd']
for i in range(len(my_list)):
my_list[i] = my_list[i] * 2
Examples of Complex Manipulations
With indexes, you can easily implement algorithms that require simultaneous access to multiple list elements, for instance, to compare the current element with the previous or next one:
Example:
my_list = [3, 5, 2, 9, 4]
for i in range(1, len(my_list)):
if my_list[i] > my_list[i - 1]:
print(f'{my_list[i]} is greater than {my_list[i - 1]}')
6.3 Using enumerate()
In Python, the
enumerate()
function provides a convenient
way to iterate over a list's items while simultaneously accessing their indexes.
This is especially useful when you need to process both the index and the element
value within the loop.
enumerate()
Basics
The enumerate()
function wraps a list into a special object and
returns an iterator that produces tuples (pairs of values), consisting of
the index and the element's value:
my_list = ["apple", "banana", "cherry"]
for index, element in enumerate(my_list):
print(f'Index: {index}, Element: {element}')
Now you have not just the element, but also its index.
Advantages of enumerate()
Using enumerate()
makes the code more readable and
allows you to avoid manually managing indexes with
range(len(...))
. This simplifies list element manipulations,
such as modification, element access, and conditional checks.
Usage Examples
enumerate()
is perfect for tasks where you need to
simultaneously modify list elements or compare elements with their
indexes:
my_list = ["apple", "banana", "cherry"]
for index, element in enumerate(my_list):
if index % 2 == 0:
print(f'Element {element} at even index {index}')
6.4 while
Loop
We've discussed for
, so let's talk about the while
loop. This loop can also be useful when working with list elements.
Remember, a while
loop starts by checking a condition.
If the condition is true, the loop body is executed, and then the condition
is checked again. The process repeats until the condition becomes
false.
Example of Iterating Through a List
Let's say you have a list of numbers, and you want to iterate through it until you encounter a specific value:
numbers = [1, 2, 3, 4, 5, -1, 6]
i = 0
while i < len(numbers) and numbers[i] != -1:
print(numbers[i])
i += 1
Not too different from a for
loop, right? But there are cases where we don't
need to use an index to work with list elements. For instance, if the list stores tasks,
you need to take them one by one, execute, and then remove them from the list.
You could write this code schematically like this:
tasks = [1, 2, 3, 4, 5, -1, 6]
while len(tasks) > 0:
task = tasks.pop()
print(task)
GO TO FULL VERSION