Fundamentals 4 min read

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.

AI Large-Model Wave and Transformation Guide
AI Large-Model Wave and Transformation Guide
AI Large-Model Wave and Transformation Guide
How to Loop Through a Python List Using for and while

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
2

This 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 times

The article warns that the loop condition must eventually become false; otherwise the program would run indefinitely and could crash.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonprogrammingListfundamentalsLoopsfor loopwhile-loop
AI Large-Model Wave and Transformation Guide
Written by

AI Large-Model Wave and Transformation Guide

Focuses on the latest large-model trends, applications, technical architectures, and related information.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.