The Wayback Machine - https://web.archive.org/web/20240827220302/https://www.geeksforgeeks.org/loop-through-a-list-using-while-loop-in-python/
Open In App

Loop Through a List using While Loop in Python

Last Updated : 07 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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]



Similar Reads

Difference between for loop and while loop in Python
In this article, we will learn about the difference between for loop and a while loop in Python. In Python, there are two types of loops available which are 'for loop' and 'while loop'. The loop is a set of statements that are used to execute a set of statements more than one time. For example, if we want to print "Hello world" 100 times then we ha
4 min read
Multiplication Table Using While Loop in Python
Multiplication tables are fundamental in mathematics, serving as the building blocks for more advanced concepts. In Python, we can use various methods to generate multiplication tables, and one versatile tool for this task is the 'while' loop. In this article, we will explore some commonly used and straightforward methods to create multiplication t
3 min read
Python Program to Find the Sum of Natural Numbers Using While Loop
Calculating the Sum of N numbers in Python using while loops is very easy. In this article, we will understand how we can calculate the sum of N numbers in Python using while loop. Calculate Sum of Natural Numbers in Python Using While LoopBelow are some of the examples by which we can see how we can calculate the sum of N numbers in Python: Exampl
2 min read
Decrement in While Loop in Python
A loop is an iterative control structure capable of directing the flow of the program based on the authenticity of a condition. Such structures are required for the automation of tasks. There are 2 types of loops presenting the Python programming language, which are: for loopwhile loop This article will see how to decrement in while loop in Python.
3 min read
How to Kill a While Loop with a Keystroke in Python?
Loops are fundamental structures in Python programming for executing a block of code repeatedly until a certain condition is met. However, there are scenarios where you might want to terminate a while loop prematurely, especially when you want to give the user the ability to interrupt the loop with a keystroke. In this article, we'll explore some s
3 min read
How to Parallelize a While loop in Python?
Parallelizing a while loop in Python involves distributing the iterations of a loop across multiple processing units such as the CPU cores or computing nodes to execute them concurrently. This can significantly reduce the overall execution time of the loop, especially for tasks that are CPU-bound or require heavy computation. In this article, we'll
2 min read
How to Emulate a Do-while loop in Python?
We have given a list of strings and we need to emulate the list of strings using the Do-while loop and print the result. In this article, we will take a list of strings and then emulate it using a Do-while loop. Do while loop is a type of control looping statement that can run any statement until the condition statement becomes false specified in t
3 min read
Python While Loop
Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed. Syntax of while loop in Pythonwhile expression: statement(s)Flowchart of Python While Loop While loop falls under the category of indefinite ite
9 min read
Python - Loop through files of certain extensions
A directory is capable of storing multiple files and python can support a mechanism to loop over them. In this article, we will see different methods to iterate over certain files in a given directory or subdirectory. Path containing different files: This will be used for all methods. Method 1: Using listdir() In this method, we will use the os.lis
4 min read
Python Loop through Folders and Files in Directory
File iteration is a crucial process of working with files in Python. The process of accessing and processing each item in any collection is called File iteration in Python, which involves looping through a folder and perform operation on each file. In this article, we will see how we can iterate over files in a directory in Python. Python Loop thro
4 min read
Loop through a JSON array in Python
A JSON array is an ordered list of values that can store multiple values such as string, number, boolean, or object. The values in a JSON array must be separated by commas and enclosed in squares in brackets []. In this article, we will learn how we can loop through a JSON array in Python. Iterate over a JSON object in PythonArrays in JSON are almo
4 min read
Loop Through a Nested Dictionary in Python
Working with nested dictionaries in Python can be a common scenario, especially when dealing with complex data structures. Iterating through a nested dictionary efficiently is crucial for extracting and manipulating the desired information. In this article, we will explore five simple and generally used methods to loop through a nested dictionary i
3 min read
How to loop through each row of dataFrame in PySpark ?
In this article, we are going to see how to loop through each row of Dataframe in PySpark. Looping through each row helps us to perform complex operations on the RDD or Dataframe. Creating Dataframe for demonstration: C/C++ Code # importing necessary libraries import pyspark from pyspark.sql import SparkSession # function to create new SparkSession
5 min read
Python - Iterate through list without using the increment variable
Python Lists is much like flexible size arrays, declared in other languages like vector in C++, array list in Java, etc. Lists are heterogeneous, making it the most effective feature in Python. Lists are mutable, and hence can be modified even after they have been formed. The most common approach is to iterate through a list using the increment var
2 min read
Handling Access Denied Error Occurs While Using Subprocess.Run in Python
In Python, the subprocess module is used to run new applications or programs through Python code by creating new processes. However, encountering an "Access Denied" error while using subprocess.run() can be problematic. This error arises due to insufficient permissions for the user or the Python script to execute the intended command. In this artic
5 min read
How to iterate through a nested List in Python?
In this article, we are going to see how to iterate through a nested List. A list can be used to store multiple Data types such as Integers, Strings, Objects, and also another List within itself. This sub-list which is within the list is what is commonly known as the Nested List. Iterating through a Nested List Lets us see how a typical nested list
2 min read
How we can iterate through list of tuples in Python
In this article, we will discuss different ways to iterate the list of tuples in Python. It can be done in these ways: Using Loop.Using enumerate().Method 1: Using Loop Here we are going to form a list of tuples using for loop. C/C++ Code # create a list of tuples with student # details name = [('sravan',7058,98.45), ('ojaswi',7059,90.67), ('bobby'
2 min read
Iterate through list of dictionaries in Python
In this article, we will learn how to iterate through a list of dictionaries. List of dictionaries in use: [{'Python': 'Machine Learning', 'R': 'Machine learning'}, {'Python': 'Web development', 'Java Script': 'Web Development', 'HTML': 'Web Development'}, {'C++': 'Game Development', 'Python': 'Game Development'}, {'Java': 'App Development', 'Kotli
3 min read
How to preserve Function Metadata while using Decorators?
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it.Note: For more information, refer Decorators in Python How to preserve Metadata? This
2 min read
How to skip rows while reading csv file using Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. Pandas package is one of them and makes importing and analyzing data so much easier. Here, we will discuss how to skip rows while reading csv file. We will use read_csv() method of Pandas library for this task. Syntax: pd.read_csv(fil
3 min read
PyQt5 - How to automate Progress Bar while downloading using urllib?
PyQt5 is one of the emerging GUI libraries in terms of developing Python GUI Desktop apps. It has rich and robust functionality which ensures production quality apps. Learning PyQt5 library is an add-on to your knowledge. You can develop your consumer quality, highly professional apps. In this article, we will learn how to automate the Progress Bar
3 min read
Python | Delete items from dictionary while iterating
A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple. Note: In Python 2 dictionary keys were unordered. As of Python 3, they
3 min read
Python | Avoiding quotes while printing strings
We often come across small issues that turn out to be big. While coding, the small tasks become sometimes tedious when not handled well. One of those tasks is output formatting in which we require to omit the quotes while printing any list elements using Python. Example Input : ['Geeks', 'For', 'Geeks'] Output : Geeks For GeeksAvoiding Quotes While
4 min read
When not to use Recursion while Programming in Python?
To recurse or not to recurse, that is the question. We all know about the fun we have with recursive functions. But it has its own set of demerits too, one of which is going to be explained in this article to help you choose wisely. Say, we need to create a function which when called needs to print the data in a linked list. This can be done in 2 w
3 min read
How to use while True in Python
In this article, we will discuss how to use while True in Python. While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever. Example: While Loop with True C/C++ Code # Python program to demonstrate # while loop with True while True: pass If we run
2 min read
Python While Else
Python is easy to understand and a robust programming language that comes with lots of features. It offers various control flow statements that are slightly different from those in other programming languages. The "while-else" loop is one of these unique constructs. In this article, we will discuss the "while-else" loop in detail with examples. Wha
6 min read
Loops in Python - For, While and Nested Loops
Python programming language provides two types of Python loopshecking time. In this article, we will look at Python loops and understand their working with the help of examp - For loop and While loop to handle looping requirements. Loops in Python provides three ways for executing the loops. While all the ways provide similar basic functionality, t
11 min read
How to fix "error 403 while installing package with Python PIP"?
When working with Python, pip is the go-to tool for managing packages. However, encountering a "403 Forbidden" error can be frustrating. This error typically indicates that the server refuses to fulfill the request, often due to permissions or access restrictions. In this article, we'll delve into the causes of this error and explore various soluti
4 min read
Python Do While Loops
In Python, there is no construct defined for do while loop. Python loops only include for loop and while loop but we can modify the while loop to work as do while as in any other languages such as C++ and Java. In Python, we can simulate the behavior of a do-while loop using a while loop with a condition that is initially True and then break out of
6 min read
Python - Create list of tuples using for loop
In this article, we will discuss how to create a List of Tuples using for loop in Python. Let's suppose we have a list and we want a create a list of tuples from that list where every element of the tuple will contain the list element and its corresponding index. Method 1: Using For loop with append() method Here we will use the for loop along with
2 min read
Article Tags :
Practice Tags :