Use for
loop statement to iterate the list items in python.
colors_list = ["Red", "Blue", "Green"]
for color in colors_list:
print(color)
Red
Blue
Green
In the above example, we are iterating the colors_list
by using the for
loop statement and printing the items from the list.
You can also fetch list items by referring its the index number while iterating the loop.
colors_list = ["Red", "Blue", "Green"]
for i in range(len(colors_list)):
print(colors_list[i])
Red
Blue
Green
For the iteration of for loop, we used range()
and len()
methods. Here range()
function represents an immutable sequence of numbers, and len()
returns the number of items in the list.
This example creates an iterable with values of [0, 1, 2]
.
For looping through lists, list comprehension offers the shortest syntax.
While using list comprehension, you're for loop code should be enclosed in square brackets.
colors_list = ["Red", "Blue", "Green"]
[print(color) for color in colors_list]
Red
Blue
Green
In the above example, we are iterating the colors_list
by using the for
loop statement with List Comprehension and printing the items from the list.
You can also use the while
loop statement to iterate the list items in python.
While iterating the list items using the while
loop, use the len()
function to determine the number of items in the list, then start loop iteration from 0
using temporary variable declarations and increment that variable by 1
for each iteration.
colors_list = ["Red", "Blue", "Green"]
i = 0
while i < len(colors_list):
print(colors_list[i])
i = i + 1
Red
Blue
Green
In the above example, we are iterating the colors_list
by using the while
loop statement and printing the items from the list.