Hey! If you love Python and building Python apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

How to Iterate Over a List in Python

Learn how to iterate over lists, tuples, and other iterable objects in Python with ease. …


Updated May 10, 2023

Learn how to iterate over lists, tuples, and other iterable objects in Python with ease.

Definition of Iterating Over a List

Iterating over a list means accessing each element of the list one by one, without having to explicitly reference them by their index. This is particularly useful when working with large datasets or when you need to perform an operation on every item in a collection.

Step-by-Step Explanation

To iterate over a list in Python, you can use a for loop. Here’s the basic syntax:

# Define a sample list
fruits = ['apple', 'banana', 'cherry']

# Iterate over the list using a for loop
for fruit in fruits:
    print(fruit)

Let’s break this down step by step:

  1. Define a list: First, we define a list fruits containing some string values.
  2. Use a for loop: Then, we use a for loop to iterate over the elements of the list.
  3. Iterate over each item: Inside the loop, we assign each element of the list to a variable named fruit. This is called binding or assignment.
  4. Perform an action on each item: Finally, we print out the value of fruit, which represents each individual element in the list.

When you run this code, it will output:

apple
banana
cherry

Using Indexing vs Iterating

While indexing allows you to access elements by their position using square brackets [] (e.g., fruits[0]), iterating provides more flexibility and readability. Here’s an example of how you might use indexing to print out the first three elements:

for i in range(3):
    print(fruits[i])

However, this approach can become cumbersome when working with larger lists or when performing complex operations.

Iterating Over Tuples

Tuples are similar to lists but cannot be modified once created. You can iterate over tuples just like lists:

colors = ('red', 'green', 'blue')
for color in colors:
    print(color)

Output:

red
green
blue

Iterating Over Other Iterable Objects

Not only can you iterate over lists and tuples, but also other iterable objects like sets, dictionaries, and generators. Let’s see an example with a set:

numbers = {1, 2, 3, 4, 5}
for num in numbers:
    print(num)

Output:

1
2
3
4
5

As you can see, iterating over sets simply returns each unique element.

Conclusion

In this article, we’ve covered how to iterate over lists and other iterable objects in Python. This fundamental concept is essential for working with collections of data, making it easier to perform operations on every item in a dataset.

Stay up to date on the latest in Python, AI, and Data Science

Intuit Mailchimp