How to Iterate List in Python

1. Introduction

Iterating through a list is a basic operation in Python that allows programmers to perform actions on each item of the list. Whether it's for processing data, searching for items, or manipulating list elements, understanding how to iterate through lists is crucial in Python programming.

Definition

Iteration, in the context of a Python list, means going through the list elements one by one. Python provides several methods to iterate over lists, such as using the for loop, while loop, list comprehensions, and built-in functions like map.

2. Program Steps

1. Create a list to iterate over.

2. Use a for loop to iterate through each element of the list.

3. Use a while loop to iterate through the list based on index.

4. Apply list comprehension for iteration and perform operations on the list.

5. Use the map() function to apply a function to each item in the list.

3. Code Program

# Step 1: Create a list
my_list = [1, 2, 3, 4, 5]

# Step 2: Use a for loop to iterate through each element
print("For loop iteration:")
for item in my_list:
    print(item)

# Step 3: Use a while loop for iteration based on index
print("\nWhile loop iteration:")
index = 0
while index < len(my_list):
    print(my_list[index])
    index += 1

# Step 4: Use list comprehension to create a new list with squared values
squared_list = [x**2 for x in my_list]

# Step 5: Print the list with squared values
print("\nList after squaring with list comprehension:")
print(squared_list)

# Step 6: Use the map() function to apply a function to each item
incremented_list = list(map(lambda x: x + 1, my_list))

# Step 7: Print the list after map operation
print("\nList after incrementing with map:")
print(incremented_list)

Output:

For loop iteration:
1
2
3
4
5
While loop iteration:
1
2
3
4
5
List after squaring with list comprehension:
[1, 4, 9, 16, 25]
List after incrementing with map:
[2, 3, 4, 5, 6]

Explanation:

1. my_list is defined with integers from 1 to 5.

2. The for loop prints each item directly from my_list.

3. The while loop uses an index to access each element by its position until it reaches the end of the list.

4. squared_list is created by squaring each element of my_list using list comprehension.

5. squared_list is printed to show the result of the list comprehension operation.

6. incremented_list is created using the map() function with a lambda that increments each element.

7. incremented_list is printed, showing each original element from my_list incremented by 1.

Comments