For Loops in List


Iterating/looping over a list in Python is a fundamental concept that allows you to access and manipulate each element in the list.

Using a for loop

The simplest and most common way to iterate over a list is by using a for loop.

names= ["ram", "sham", "merry"]

for name in names:
    print(name)

Here name takes on the value of each element in the names list in turn, and print(name) outputs each name to the command line.


Using the range function with a for loop

Sometimes, you may need to iterate over the indices of a list rather than the elements themselves.

You can use the range function combined with len to achieve this.

names= ["ram", "sham", "merry"]

for i in range(len(names)):
    print(names[i])

Here, len returns the length of names list, using the len , range function creates numbers from 0 to given len of list.

finally names[i] prints outs output on command line.


Iterating with Index using enumerate

If you need both the elements and their indices from the list, you can use the enumerate function.

# Example list
names= ["ram", "sham", "merry"]

# Using a for loop with enumerate to iterate through the list with indices
for index, item in enumerate(names):
    print(f"Index {index}: {item}")


Nested Lists

If your list contains nested lists (lists within a list), you can use nested for loops to iterate through them.

# Example nested list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Using nested for loops to iterate through the nested list
for inner_list in nested_list:
    for item in inner_list:
        print(item)