How to Loop Through a Python List Using for and while
This guide demonstrates how to define a Python list, print its contents, and iterate over each element using both a for‑loop and a while‑loop, including step‑by‑step code explanations and common pitfalls such as infinite loops and type conversion.
First, a list containing mixed types is defined and printed to show its structure:
list = ["a", 1, "b", 2]
print(list)The output is ['a', 1, 'b', 2], confirming that Python lists can store heterogeneous elements.
To access each element sequentially, a for loop is used. The loop variable element receives one item from the list on each iteration, and print(element) outputs it:
list = ["a", 1, "b", 2]
for element in list:
print(element)The resulting lines are:
a
1
b
2This demonstrates that the for construct automatically traverses the entire list without manual indexing.
Next, a while loop example shows how to repeat a block while a condition holds. The variable num starts at 0, and the loop continues while num < 5:
num = 0
while num < 5:
num = num + 1
print("Executed " + str(num) + " times")During each iteration, num is incremented, then converted to a string with str(num) so it can be concatenated with other strings—an important step because Python does not allow direct concatenation of integers and strings.
The loop prints:
Executed 1 times
Executed 2 times
Executed 3 times
Executed 4 times
Executed 5 timesThe article warns that the loop condition must eventually become false; otherwise the program would run indefinitely and could crash.
AI Large-Model Wave and Transformation Guide
Focuses on the latest large-model trends, applications, technical architectures, and related information.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
