Python for Loop In List

Python provides the list type in order to store multiple items in a single variable or object. The list type is an iterable type that can be iterated with the for loop . By using the for loop we can iterate over the items of the specified list.

Iterate List with for Loop

The for loop can be used to iterate over a Python list. Simply we provide the list into the for loop and iterate to the next item in every step. In the following example we iterate over a number list.

numbers=[1,2,3,4,5,6,7,8,9]

for a in numbers:
   print(a)
Iterate List with for Loop

Iterate List with for Loop Using range()

The Python for loop is designed to work with iterable values. which is a bit different from other mainstream programming languages. But we can use the range() function in order to a list of numbers those can be used like index numbers and iterate over the list. We use the range() function in order to create a list of numbers in a ordered way. In the following example we iterate over list from index numbers 0 to 5 .

numbers=[1,2,3,4,5,6,7,8,9]

for i in range(0,5):
   print(numbers[i])
Iterate List with for Loop Using range()

Iterate List with for Loop Using enumerate()

Python provides the enumerate() function which can be used to return the index number with the items. The returned index number and item is returned as tuple.

numbers=[1,2,3,4,5,6,7,8,9]

for i,item in enumerate(numbers):
   print("Index number is ",i," and value is ",item)
Iterate List with for Loop Using enumerate()

Iterate List with Comprehension

Python provides the list comprehension in order to iterate over a list. Even it is not direcly related with the for loop we can use the list comprehension in order to iterate over a list.

numbers=[1,2,3,4,5,6,7,8,9]

[print(i) for i in numbers]
Iterate List with Comprehension

Leave a Comment