Open In App

Loop Through a List using While Loop in Python

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, the while loop is a versatile construct that allows you to repeatedly execute a block of code as long as a specified condition is true. When it comes to looping through a list, the while loop can be a handy alternative to the more commonly used for loop. In this article, we’ll explore four simple examples of how to loop through a list using the while loop in Python.

Loop Through A List Using While Loop In Python

Below, are the ways to Loop Through A List Using While Loop In Python.

  • Basic List Iteration
  • Looping with a Condition
  • Modifying List Elements
  • User Input in Loop

Basic List Iteration

In this example, we initialize an index variable to 0 and use a while loop to iterate through the list until the index exceeds the length of the list. The value at the current index is printed, and the index is incremented in each iteration

Python3




# Basic List Iteration
my_list = [1, 2, 3, 4, 5]
index = 0
 
while index < len(my_list):
    print(my_list[index])
    index += 1


Output

1
2
3
4
5


Loop Through A List Using While Loop by Looping with a Condition

This example demonstrates how to loop through a list with a condition. Here, we print only the elements of the list that have a length greater than 5 characters.

Python3




#Looping with a Condition
fruits = ["apple", "banana", "orange", "grape"]
index = 0
 
while index < len(fruits):
    if len(fruits[index]) > 5:
        print(fruits[index])
    index += 1


Output

banana
orange


Loop Through A List Using While Loop by Modifying List Elements

In this example, the while loop is used to modify the elements of the list. Each element is multiplied by 2, resulting in a list where every value has been doubled

Python3




# Modifying List Elements
numbers = [1, 2, 3, 4, 5]
index = 0
 
while index < len(numbers):
    numbers[index] *= 2  # Multiply each element by 2
    index += 1
 
print(numbers)


Output

[2, 4, 6, 8, 10]


Loop Through A List Using While Loop by User Input in Loop

Here, the while loop is used to continuously prompt the user for input until they enter “done.” The entered numbers are converted to integers and added to a list.

Python3




# User Input in Loop
user_list = []
user_input = input("Enter a number (type 'done' to finish): ")
 
while user_input.lower() != 'done':
    user_list.append(int(user_input))
    user_input = input("Enter another number (type 'done' to finish): ")
 
print("User's List:", user_list)


Output

Enter a number (type 'done' to finish): 3
Enter another number (type 'done' to finish): 3
Enter another number (type 'done' to finish): done
User's List: [3, 3]



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads