VMware ESXi and vSphere Cluster Management

How to Loop Through a List in Python

Learn how to use Python for loops to process every list item, print values, apply operations, test membership, and avoid common beginner mistakes.

A Python list is an ordered, mutable collection that can contain multiple values. For example, a list can store several names, prices, or scores:

names = ["Ava", "Ben", "Mia"]

To work with every value in a list, use a for loop. Looping through a list is called iteration: Python visits the elements one at a time and runs the loop body for each element.

Why Loop Through a List?

A loop lets you repeat an action without writing separate code for every item. Common uses include:

  • Displaying every value.
  • Checking whether each value meets a condition.
  • Formatting each item into a message.
  • Calculating a derived value, such as a tax-inclusive price.
  • Collecting transformed or selected values in another list.

A list is an iterable, meaning that Python can visit its values in sequence. Other iterables include strings, tuples, and some dictionary views, but this lesson focuses on lists.

Basic Python for-Loop Syntax

The basic form is:

for item in items:
    # statements that run once for each item

The loop variable, item, receives the current list element. The in keyword tells Python which iterable to visit. The expression after in, such as items, is the list being processed. The colon starts the loop body, and the indented statements beneath it belong to the loop.

Code partRoleExample meaning
forStarts a for loop.Python should repeat a block of code.
Loop variableTemporary name for the current element.item means one value from the list.
inConnects the loop variable to the iterable.Take values from the list one at a time.
List variable or iterableThe sequence of values to visit.items is the list being traversed.
ColonMarks the beginning of the loop body.: tells Python a block follows.
Indented bodyContains the statements repeated for each value.print(item) runs once per element.

How List Iteration Works

Consider this loop:

colors = ["red", "green", "blue"]

for color in colors:
    print(color)

Python processes it in this order:

  1. Assign "red" to color and run the indented body.
  2. Assign "green" to color and run the body again.
  3. Assign "blue" to color and run the body again.
  4. Stop after the final list element has been processed.

The loop variable holds only one element at a time. On the next iteration, Python replaces its value with the next element.

Print Every Item in a List

Use a singular, meaningful loop variable when the list variable is plural:

names = ["Ava", "Ben", "Mia"]

for name in names:
    print(name)

Conceptual output:

Ava
Ben
Mia

names refers to the complete list, while name refers to the current item. Descriptive names such as name and price make the code easier to read than vague names such as x.

Run an Operation for Each Item

Everything in the indented loop body runs once per list item. The operation does not have to be a simple print.

Create a Message for Each Name

guests = ["Ava", "Ben", "Mia"]

for guest in guests:
    message = f"Welcome, {guest}!"
    print(message)

Each iteration creates a message using the current value of guest.

Calculate a Value for Each Price

prices = [10.00, 25.50, 8.75]
tax_rate = 0.08

for price in prices:
    total = price * (1 + tax_rate)
    print(f"${total:.2f}")

For each price, the loop calculates a tax-inclusive total and displays it. The original list is not changed by this example; total is a value calculated for the current iteration.

Check a Condition for Each Item

scores = [45, 72, 91]

for score in scores:
    if score >= 60:
        print(f"{score} passes")
    else:
        print(f"{score} needs more practice")

An if statement is a conditional statement: it runs code only when its Boolean condition is true. Here, the condition is checked separately for every score.

Membership Testing with in

The in keyword also acts as a membership operator. In an expression such as name in names, it checks whether one particular value occurs in the list and produces either True or False.

names = ["Ava", "Ben", "Mia"]
proposed_name = "Ben"

if proposed_name in names:
    print("That name is already in the list.")

This is different from a for loop. A membership test answers whether one target exists; it does not visit every item for you and does not automatically print matching values.

GoalRecommended constructResult
Process every itemfor item in items:Runs the loop body once for each item.
Determine whether one value existstarget in itemsProduces True or False.
Run code for each matching or nonmatching itemA for loop containing an if statementChecks each item and runs the appropriate conditional body.

Prevent a Duplicate Name

names = ["Ava", "Ben"]
proposed_name = "Mia"

if proposed_name in names:
    print("Choose a different name.")
else:
    names.append(proposed_name)
    print("Name added.")

The value is tested against the intended list. When it is absent, append() adds it to the list. A duplicate check only prevents duplicates if the list is updated after an accepted value.

Common Beginner Mistakes

Incorrect or Missing Indentation

Python uses indentation, or leading whitespace, to define which statements belong to a block. Indent the loop body consistently, usually with four spaces:

names = ["Ava", "Ben"]

for name in names:
    print(name)

If the body is not indented, Python can raise an IndentationError. Mixing indentation styles can also cause errors. Configure your editor to insert spaces consistently.

Using the Loop Variable Before the Loop

The loop assigns the variable when iteration begins. Do not expect name to represent a list item before this loop has run:

names = ["Ava", "Ben"]

# Incorrect idea: name has not been assigned by a loop yet
# print(name)

for name in names:
    print(name)

Confusing the List with the Current Item

Use the plural list variable to refer to all values and the singular loop variable to refer to one value:

prices = [10, 20, 30]

for price in prices:
    print(price)       # current number
    print(prices)      # complete list

Printing prices inside the loop prints the complete list repeatedly. To display each individual value, print price.

Expecting Membership Testing to Process Every Match

This condition only answers whether the target exists:

if "Ben" in names:
    print("Ben exists")

To perform an action for every item that matches a condition, use a loop:

names = ["Ben", "Ava", "Ben"]

for name in names:
    if name == "Ben":
        print("Found Ben")

Comparing Strings with the Wrong Capitalization

String comparisons are case-sensitive. "ben" == "Ben" is false because the letters have different capitalization. Normalize values when your application should treat capitalization as irrelevant:

names = ["Ava", "Ben", "Mia"]
proposed_name = " ben "

clean_name = proposed_name.strip().lower()
normalized_names = [name.lower() for name in names]

if clean_name in normalized_names:
    print("That name is already present.")

strip() removes surrounding whitespace, and lower() converts letters to lowercase. Apply normalization consistently to both the proposed value and the values being checked.

Quick Reference

items = [item_a, item_b, item_c]

for item in items:
    # process item here
    print(item)
  • Iteration visits list elements one at a time.
  • The loop variable receives the current element.
  • The indented body runs once for every element.
  • The loop ends after the final element.
  • Use value in list_name when you need a membership result for one value.
  • Use a loop with an if statement when you need to process items according to a condition.

For more list practice, continue with looping through a Python list and then explore related techniques such as indexes, enumerate(), nested loops, and list comprehensions.