Python provides multiple ways to loop through a list depending on the requirement.
Let’s explore them one by one.
Loop through List Items :
Python
fruits = ["apple", "banana", "mango"] for fruit in fruits: print(fruit) #output apple banana mango Loop through List using index :
Python
numbers = [10, 20, 30] for i in range(len(numbers)): print(i, numbers[i]) #output 0 10 1 20 2 30 Loop using enumerate() :
enumerate() gets the index and value together.
Python
colors = ["red", "green", "blue"] for index, value in enumerate(colors): print(index, value) #output 0 red 1 green 2 blue Using While Loop :
Python
cars = ["BMW", "Audi", "Tesla"] i = 0 while i < len(cars): print(cars[i]) i += 1 #output BMW Audi Tesla Loop using List Comprehension :
Python
numbers = [1, 2, 3] squares = [n*n for n in numbers] print(squares) #output [1, 4, 9] Loop through Nested List :
Python
matrix = [[1, 2], [3, 4]] for row in matrix: for val in row: print(val) #output 1 2 3 4