Loop Through List of Integers in Python (3 Examples)

In this tutorial, youâ€™ll learn how to loop through a list of integers in Python and perform operations on each element within the list. Weâ€™ll explore different examples to demonstrate this concept.

Letâ€™s dive into it!

Creating Sample Data

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

We have created a simple list of integers to use in our examples.

Example 1: Looping Through a List

The first example involves looping through a list of integers using a for loop. Hereâ€™s how it works:

```for num in numbers:
print(num)
# 1
# 2
# 3
# 4
# 5```

In this example, we have a list of integers called `numbers`. The `for` loop iterates over each element in the list, and we print each value of `num`.

Example 2: Looping Through a List with Index

The second example demonstrates how to loop through a list of integers and access the index and value of each element. Hereâ€™s an example:

```for index, num in enumerate(numbers):
print(f"Index: {index}, Value: {num}")
# Index: 0, Value: 1
# Index: 1, Value: 2
# Index: 2, Value: 3
# Index: 3, Value: 4
# Index: 4, Value: 5```

In this example, we use the enumerate() function to get both the index and value of each element in the list. The loop iterates over the list, and for each iteration, we print the index and value. For further details, see Loop Over List with Index in Python.

Example 3: Looping Through a List with Conditional Statements

The third example demonstrates how to loop through a list of integers and perform operations based on conditional statements. Hereâ€™s an example:

```for num in numbers:
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
# 1 is odd
# 2 is even
# 3 is odd
# 4 is even
# 5 is odd```

In this example, we loop through the list of integers. We use an `if` statement to check if the number is even or odd, and we print the corresponding message based on the condition.

Video, Further Resources & Summary

Do you need more explanations on looping through a list of integers in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

Furthermore, you could have a look at some of the other tutorials on Statistics Globe:

This post has shown how to loop through a list of integers in Python. In case you have further questions, you may leave a comment below.

This page was created in collaboration with Ã–mer Ekiz. Have a look at Ã–merâ€™s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.

Subscribe to the Statistics Globe Newsletter