How do I iterate over lists in Python for beginners?

In Python, you can iterate over lists using several methods. Here, we'll discuss a few common ways to loop through elements in a list. This is fundamental for beginners learning Python programming.

One of the simplest ways to iterate over a list is by using a for loop. Here’s how you can do it:

# Example of iterating over a list in Python fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)

In this example, the for loop goes through each item in the fruits list and prints it.

Another method is using the enumerate() function, which is useful if you need the index of each item:

# Example with enumerate fruits = ["apple", "banana", "cherry"] for index, fruit in enumerate(fruits): print(index, fruit)

This will print both the index and the fruit name.

You can also use a while loop to iterate through a list:

# Example using while loop fruits = ["apple", "banana", "cherry"] index = 0 while index < len(fruits): print(fruits[index]) index += 1

This example shows how to increment an index manually until it reaches the end of the list.


Python iterate lists beginners for loop enumerate while loop