Skip to main content

How to loop through a list in Python

How to loop through a list in Python.

Here's a step-by-step tutorial on how to loop through a list in Python:

1: Create a list

First, you need to create a list in Python. A list is a collection of items enclosed in square brackets [] and separated by commas. For example, let's create a list of numbers:

numbers = [1, 2, 3, 4, 5]

2: Using a for loop

The most common way to loop through a list in Python is by using a for loop. The for loop allows you to iterate over each item in the list.

for item in numbers:
# Code to be executed for each item
print(item)

In this example, the variable item represents each item in the list numbers. The code inside the for loop (indicated by the indentation) is executed for each item in the list. In this case, we are simply printing each item.

3: Accessing the index

Sometimes, you might need to access both the index and the value of each item in the list. You can use the enumerate() function to achieve this.

for index, item in enumerate(numbers):
# Code to be executed for each item
print(f"Index: {index}, Item: {item}")

In this example, the enumerate() function returns a tuple containing the index and item for each iteration. We can then unpack this tuple into variables index and item to access both the index and the value of each item.

4: Looping through a subset of the list

If you only want to loop through a subset of the list, you can use slicing to extract a portion of the list. Slicing allows you to specify a start and end index to loop through only a part of the list.

for item in numbers[2:4]:
# Code to be executed for each item
print(item)

In this example, we are using slicing to loop through only the items at index 2 and 3 ([2:4]) of the list numbers.

5: Using a while loop

Alternatively, you can use a while loop to iterate through a list. The while loop allows you to repeat a block of code until a certain condition is met.

index = 0
while index < len(numbers):
item = numbers[index]
# Code to be executed for each item
print(item)
index += 1

In this example, we initialize a variable index to 0 and increment it by 1 in each iteration until it reaches the length of the list. We then use this index to access each item in the list and perform the desired operations.

That's it! You now know how to loop through a list in Python using both for and while loops.