HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Python Loop Lists

Looping through lists in Python is commonly done using either a for loop or a while loop.

Loop Through a List

You can loop through the list items by using a for loop:

Example
# Creating a list
my_list = ['apple', 'banana', 'cherry', 'date']

# Looping through the list using a for loop
for item in my_list:
    print(item)
   
Output:  
apple
banana
cherry
date

                 
              

Using a While Loop

Using a while loop with an index:

Example
# Creating a list
my_list = ['apple', 'banana', 'cherry', 'date']

# Initializing index
index = 0:
    print(item)
 # Looping through the list using a while loop
while index < len(my_list):
    print(my_list[index])
    index += 1

Output:
apple
banana
cherry
date

              

Loop Through the Index Numbers

You can also loop through the list items by referring to their index number.

Use the range() and len() functions to create a suitable iterable.

Example
# Creating a list
my_list  = ['apple', 'banana', 'cherry', 'date']

for i in range(len(my_list)):

    print(my_list[i])  
    
    Output
    apple 
    banana
    cherry
    date