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 List in Python

Learn the fundamental concept of iterating over lists in Python, a crucial skill for any aspiring programmer. …


Updated July 28, 2023

Learn the fundamental concept of iterating over lists in Python, a crucial skill for any aspiring programmer.

Definition of Iterating Over Lists

Iterating over a list in Python means accessing each element one by one, without having to manually specify the index. This process is essential for performing various operations on lists, such as printing elements, calculating sums, or searching for specific values.

Step-by-Step Explanation: Using for Loops

The most common method for iterating over a list in Python is by using a for loop. Here’s a step-by-step breakdown:

1. Syntax

for variable_name in list:
    # Code to execute on each iteration
  • variable_name: Choose a meaningful name for the variable that will hold the current element.
  • list: The list you want to iterate over.

2. Example

Let’s say we have a list of favorite fruits:

fruits = ['Apple', 'Banana', 'Cherry']

To print each fruit in the list, use the following code:

for fruit in fruits:
    print(fruit)

When you run this code, it will output:

Apple
Banana
Cherry

3. Code Explanation

  • In the first line (for fruit in fruits:), we specify that we want to iterate over the fruits list and assign each element to a variable named fruit.
  • Inside the loop, we print the current value of fruit.

Alternative Method: Using enumerate()

If you need to access both the index and the value of each element in the list, use the built-in function enumerate():

for index, fruit in enumerate(fruits):
    # Code to execute on each iteration
  • index: The current index (position) of the element.
  • fruit: The actual value of the element.

Example

Let’s print both the index and the fruit name:

fruits = ['Apple', 'Banana', 'Cherry']
for index, fruit in enumerate(fruits):
    print(f"Index: {index}, Fruit: {fruit}")

When you run this code, it will output:

Index: 0, Fruit: Apple
Index: 1, Fruit: Banana
Index: 2, Fruit: Cherry

Conclusion

Iterating over lists in Python is an essential skill for any programmer. By mastering for loops and the enumerate() function, you can efficiently process data in various applications, from simple printing to complex operations. Practice using these techniques to become proficient in list iteration.


Note: This article aims for a Fleisch-Kincaid readability score of 8-10 by using plain language and avoiding jargon.

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

Intuit Mailchimp