Python - How to loop / iterate a list

By xngo on June 12, 2019

Here are different ways to loop through a list.

#!/usr/bin/python3
 
fruits = ['pineapple', 'gava', 'apple']
 
# Loop through a list using in operator.
for item in fruits:
    print(item, end=', ')
print()
 
# Loop through a list using index and range.
for i in range(1, len(fruits)):
    print(fruits[i], end=', ')
print()
 
# Loop through a list & get index at the same time.
for (i, item) in enumerate(fruits):
    print(i, item)

Output

pineapple, gava, apple, 
gava, apple, 
0 pineapple
1 gava
2 apple

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.