|
| Home |
|---|
Looping through a Python list means processing its
elements one at a time. Python provides several ways to iterate through
list items, with the for loop being the most common and
readable approach.
List loops are useful when you need to display every item, perform a calculation, search for values, apply conditions, process records, validate data or perform an operation on each element of a collection.
Python also allows you to loop through a list using indexes,
enumerate() and while loops. The appropriate
approach depends on whether you need only the values, both the indexes
and values, or more control over the iteration process.
The simplest and most common way to loop through a Python list is
with a for loop. Python automatically assigns each list
item to the loop variable as it moves through the list.
The basic syntax is:
for item in list_name:
# code to process item
colors = ["Red", "Orange", "Yellow", "Green", "Blue"]
for color in colors:
print(color)
Red
Orange
Yellow
Green
Blue
The loop processes the first item, then the second, then the third, continuing until every element in the list has been processed.
A list loop can process numbers in exactly the same way as strings or other values.
numbers = [10, 20, 30, 40, 50]
for number in numbers:
print(number)
10
20
30
40
50
The code inside the loop can perform calculations or other operations on every element.
numbers = [10, 20, 30, 40]
for number in numbers:
print(number * 2)
20
40
60
80
Each value is multiplied by 2 as the loop processes the
list.
An if statement can be placed inside a loop to perform
an operation only when a list item meets a particular condition.
numbers = [10, 15, 20, 25, 30]
for number in numbers:
if number >= 20:
print(number)
20
25
30
This pattern is useful when searching, filtering or validating list data.
A loop can be used when you need to examine each element and perform an action when a particular value is encountered.
fruits = ["apple", "banana", "orange", "mango"]
for fruit in fruits:
if fruit == "orange":
print("Orange found")
Orange found
A normal for loop gives you the list values directly.
Sometimes, however, you also need to work with the position of each
element.
In that situation, you can iterate through a sequence of indexes
using range() and len().
colors = ["Red", "Orange", "Yellow", "Green"]
for i in range(len(colors)):
print(colors[i])
Red
Orange
Yellow
Green
Here, i represents the index and
colors[i] accesses the corresponding list item.
When you need both the position and the value of each list element,
Python's enumerate() function provides a cleaner
approach than manually creating indexes.
fruits = ["Apple", "Banana", "Orange"]
for index, fruit in enumerate(fruits):
print(index, fruit)
0 Apple
1 Banana
2 Orange
The index variable contains the position and the
fruit variable contains the corresponding value.
By default, enumerate() starts counting at
0. You can provide a different starting number when
that better matches the required output.
students = ["Ali", "Sara", "John"]
for number, student in enumerate(students, start=1):
print(number, student)
1 Ali
2 Sara
3 John
This can be useful when displaying numbered lists to users.
A while loop can also be used to process list elements.
Unlike a for loop, you must manage the index yourself.
colors = ["Red", "Orange", "Yellow", "Green"]
i = 0
while i < len(colors):
print(colors[i])
i += 1
Red
Orange
Yellow
Green
The loop continues while i is smaller than the length of
the list. After processing each item, i is increased by
one.
A for loop is usually the better choice when you simply
need to process every item in a list.
A while loop can be useful when the iteration depends on
a condition that is not simply "process every item once".
| Situation | Common Choice |
|---|---|
| Process every list item | for loop |
| Need both index and value | enumerate() |
| Need manual index control | while loop |
One common use of list loops is calculating a total from numeric values.
prices = [100, 250, 150, 300]
total = 0
for price in prices:
total += price
print(total)
800
Each price is added to total as the loop processes the
list.
A loop can also be used to calculate statistics such as an average.
scores = [70, 80, 90, 85]
total = 0
for score in scores:
total += score
average = total / len(scores)
print(average)
81.25
A counter can be used inside a loop to count how many elements satisfy a condition.
scores = [45, 72, 81, 55, 90, 38]
passed = 0
for score in scores:
if score >= 50:
passed += 1
print(passed)
4
This pattern is useful for analysing lists of scores, measurements, transactions and other numeric data.
A loop can be used to compare list elements and find a particular value.
numbers = [15, 42, 27, 63, 31]
largest = numbers[0]
for number in numbers:
if number > largest:
largest = number
print(largest)
63
numbers = [15, 42, 27, 63, 31]
smallest = numbers[0]
for number in numbers:
if number < smallest:
smallest = number
print(smallest)
15
A loop can search through list elements and stop when the required value is found.
products = ["Laptop", "Mouse", "Keyboard", "Monitor"]
for product in products:
if product == "Keyboard":
print("Product found")
break
Product found
The break statement stops the loop once the required
item has been found.
Use break when there is no need to continue processing
the remaining elements.
numbers = [10, 20, 30, 40, 50]
for number in numbers:
if number == 30:
break
print(number)
10
20
The continue statement skips the rest of the current
iteration and moves to the next list item.
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 3:
continue
print(number)
1
2
4
5
The value 3 is skipped, while the remaining items are
processed normally.
Lists containing text are commonly processed using loops.
names = ["Ali", "Sara", "John", "Ayesha"]
for name in names:
print("Student:", name)
Student: Ali
Student: Sara
Student: John
Student: Ayesha
Python lists can contain different types of values. A loop retrieves each element regardless of its type.
data = [10, "Python", 3.14, True]
for item in data:
print(item)
10
Python
3.14
True
When a list contains other lists, a nested loop can process the elements inside each inner list.
students = [
["Ali", 80],
["Sara", 92],
["John", 75]
]
for student in students:
for item in student:
print(item)
Ali
80
Sara
92
John
75
The outer loop processes each inner list, while the inner loop processes the elements inside it.
For more detailed techniques for creating and working with nested lists, see the Nested Lists tutorial.
A common programming task is to examine one list and build another list containing selected or transformed values.
numbers = [1, 2, 3, 4, 5]
squares = []
for number in numbers:
squares.append(number * number)
print(squares)
[1, 4, 9, 16, 25]
Here the loop processes each value and adds the calculated result to a new list.
A loop can be used to build a new list containing only elements that satisfy a condition.
numbers = [10, 15, 20, 25, 30]
even_numbers = []
for number in numbers:
if number % 2 == 0:
even_numbers.append(number)
print(even_numbers)
[10, 20, 30]
This pattern is widely used when filtering data according to a rule.
Lists can contain simple records represented by nested lists. A loop can process each record individually.
students = [
["Ali", 85],
["Sara", 92],
["John", 78]
]
for student in students:
print(student[0], student[1])
Ali 85
Sara 92
John 78
Each inner list represents one record, and the loop processes the records one at a time.
enumerate() is especially useful when processing a list
where the position of each element matters.
tasks = ["Login", "Download", "Process", "Save"]
for step, task in enumerate(tasks, start=1):
print("Step", step, ":", task)
Step 1 : Login
Step 2 : Download
Step 3 : Process
Step 4 : Save
This is often cleaner than manually maintaining a counter variable.
If you need to process list elements from the end toward the
beginning, Python provides reversed().
numbers = [10, 20, 30, 40]
for number in reversed(numbers):
print(number)
40
30
20
10
This processes the elements in reverse order without changing the original list.
A loop can also process a selected portion of a list. For example, a slice can be used when only part of the collection needs to be processed.
numbers = [10, 20, 30, 40, 50]
for number in numbers[1:4]:
print(number)
20
30
40
The loop processes only the selected elements. Detailed slicing techniques are covered separately in the List Slicing tutorial.
A standard for loop simply reads and processes each
element. It does not automatically modify the list.
numbers = [10, 20, 30]
for number in numbers:
print(number)
print(numbers)
10
20
30
[10, 20, 30]
The loop displays the values but leaves the original list unchanged.
A Python for statement must end with a colon.
for item in items:
print(item)
The code that belongs to the loop must be indented.
numbers = [10, 20, 30]
for number in numbers:
print(number)
When using a while loop with a list index, the counter
must be updated. Otherwise, the condition may remain true and the
loop can continue indefinitely.
numbers = [10, 20, 30]
i = 0
while i < len(numbers):
print(numbers[i])
i += 1
When manually looping through indexes, the index must remain within the valid range of the list.
numbers = [10, 20, 30]
for i in range(len(numbers)):
print(numbers[i])
Using range(len(numbers)) ensures that the generated
indexes correspond to valid positions.
Modifying the structure of a list while directly iterating through that same list can produce unexpected results because elements can shift positions as items are added or removed.
For example, removing elements during a loop can cause some elements to be skipped.
When a list needs to be filtered or transformed, it is often safer to build a new list rather than changing the collection being iterated over.
Python list comprehensions provide a compact way to create a new list from the elements of an existing list.
numbers = [1, 2, 3, 4]
squares = [number * number for number in numbers]
print(squares)
[1, 4, 9, 16]
List comprehensions are useful for concise transformations and filtering. They are covered in detail in the separate List Comprehension tutorial.
scores = [72, 85, 91, 68, 77]
for score in scores:
if score >= 80:
print("High score:", score)
High score: 85
High score: 91
prices = [450, 800, 1200, 650]
for price in prices:
if price > 700:
print(price)
800
1200
Loops can examine each value in a collection and identify values that do not meet a required condition.
ages = [18, 21, 16, 25, 17]
for age in ages:
if age < 18:
print("Under 18:", age)
Under 18: 16
Under 18: 17
transactions = [1200, 450, 800, 1500]
total = 0
for amount in transactions:
total += amount
print("Total:", total)
Total: 3950
The most common approach is to use a for loop:
for item in my_list:. The loop processes each element
one at a time.
A for loop is generally the simplest and most readable
way to iterate through all elements of a Python list.
You can use range(len(my_list)) when you specifically
need indexes. However, when both the index and value are needed,
enumerate() is usually more convenient.
Use enumerate(). For example,
for index, value in enumerate(items): provides both the
position and the corresponding list item.
Yes. A while loop can iterate through a list by using an
index and increasing that index after each iteration.
Use the break statement when a particular condition is
met. It immediately terminates the loop.
Use the continue statement. It skips the remaining code
in the current iteration and moves to the next list item.
You can use reversed(my_list) to process the elements
from the last item toward the first without modifying the original
list.
Yes. A nested loop can process the inner elements of each nested list. The outer loop processes the inner lists and the inner loop processes their elements.
You can modify list elements in some situations, but adding or removing elements from the same list while iterating through it can produce unexpected results because the list's structure changes. Building a separate list is often safer for filtering or transforming data.
A for loop is generally easier to read when the processing
involves several steps, conditions or side effects. A list
comprehension is useful when you want to create a new list from an
existing collection in a concise expression. See the separate
List Comprehension tutorial for detailed examples.
Yes. You can iterate over a selected portion of a list using slicing,
such as numbers[1:4]. More detailed slicing techniques
are covered in the separate List Slicing tutorial.
Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.
Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net