For Loop with Two Variables in Python

TLDR

  • Use dict.items() to loop over keys and values together.
  • Use enumerate() when you need the index position alongside each value.
  • Use zip() to iterate over multiple lists side by side.
  • Use range() with index to mimic traditional C-style for loops.
  • Use tuple unpacking for a, b in pairs when each item is itself a tuple or list.

Introduction

Python for loops can work with two or more variables at the same time. This is called tuple unpacking. Instead of pulling one value per iteration, you unpack multiple values from each item in the sequence.

This comes up more often than you might expect. Dictionaries give you key-value pairs. enumerate() gives you index-value pairs. zip() pairs up items from multiple lists. Python makes all of these clean and readable.

Comparison Table: Methods for Looping with Two Variables

Method Use Case Works In-Place? Returns
dict.items() Keys + values from a dictionary Yes View object
enumerate() Index + value from any sequence Yes Enumerator object
zip() Parallel iteration over multiple sequences Yes Zip object
range() + len() C-style loop with index Yes Range object
Tuple unpacking for a, b in pairs Each item is a tuple/list of two elements Yes N/A
dict.values() Values only from a dictionary Yes View object

Method 1: Using dict.items()

Dictionaries store data as key-value pairs. The items() method returns each pair as a tuple. When you loop over it with two variables, Python unpacks each tuple automatically.

person = {"Dhushi": 6, "Lee": 32, "Marc": 30}

for key, value in person.items():
    print(f"Name: {key}, Age: {value}.")

Output:

Name: Dhushi, Age: 6.
Name: Lee, Age: 32.
Name: Marc, Age: 30.

The order follows insertion order in Python 3.7+. Each iteration gives you both the key and the value without needing to index into the dictionary.

Method 2: Using enumerate()

enumerate() adds a counter to any iterable. It returns pairs of (index, value). Assign both to loop variables to get the position alongside the item.

languages = ["Python", "C", "Java", "JavaScript"]

for index, value in enumerate(languages):
    print(f"Index: {index}, Value: {value}")

Output:

Index: 0, Value: Python
Index: 1, Value: C
Index: 2, Value: Java
Index: 3, Value: JavaScript

The default start is 0. Pass a second argument to enumerate() to change the start value.

for index, value in enumerate(languages, start=1):
    print(f"#{index}: {value}")

Method 3: Using zip()

zip() takes multiple sequences and combines them element by element. Each iteration gives you one item from each sequence, packed into a tuple.

names = ["Dhushi", "Praj", "Lee"]
languages = ["Python", "JavaScript", "Java"]

for name, lang in zip(names, languages):
    print(f"My name is {name}. My favourite language is {lang}.")

Output:

My name is Dhushi. My favourite language is Python.
My name is Praj. My favourite language is JavaScript.
My name is Lee. My favourite language is Java.

The loop stops when the shortest sequence is exhausted. Use itertools.zip_longest() if you need all items from the longest sequence instead.

Method 4: Using range() with len()

If you need index-based access, range(len(sequence)) generates integer indices. Use them to index into the sequence and extract multiple values.

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]

for i in range(len(names)):
    print(f"{names[i]} scored {scores[i]}")

Output:

Alice scored 85
Bob scored 92
Charlie scored 78

This pattern is common in older Python code or when you need to modify the original sequence during iteration. For most cases, zip() is cleaner.

Method 5: Direct Tuple Unpacking

If each element in your sequence is itself a tuple or list of two items, you can unpack it directly in the for statement.

pairs = [("apple", 3), ("banana", 7), ("cherry", 2)]

for fruit, count in pairs:
    print(f"{fruit}: {count}")

Output:

apple: 3
banana: 7
cherry: 2

This works for any nested sequence. You are not limited to two variables. Python supports unpacking three or more variables as well.

triplets = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

for a, b, c in triplets:
    print(f"Sum: {a + b + c}")

Common Mistakes

Mismatched lengths with zip() silently truncates to the shortest list. If that is not what you want, check lengths first or use zip_longest().

from itertools import zip_longest

a = [1, 2, 3, 4]
b = ["x", "y"]

for num, letter in zip_longest(a, b, fillvalue="?"):
    print(f"{num} -> {letter}")

Output:

1 -> x
2 -> y
3 -> ?
4 -> ?

Unpacking a non-sequence or wrong-length sequence raises a ValueError. Always verify your data structure matches your unpacking pattern.

When to Use Each Method

Pick dict.items() for key-value dictionary iteration. Pick enumerate() when you need indices. Pick zip() for parallel iteration over multiple lists. Pick range(len()) when you need to modify the sequence by index. Pick direct tuple unpacking when your data is already organized as pairs or tuples.

FAQ: For Loop with Two Variables in Python

Can a Python for loop use two variables?

Yes. Python supports tuple unpacking in the for statement. Write for x, y in sequence and Python assigns x and y from each item in the sequence.

How do you loop through a dictionary with two variables?

Use for key, value in dict.items(). The items() method returns key-value tuples, and Python unpacks them into your two loop variables.

What does enumerate() return in Python?

enumerate() returns an iterator of tuples. Each tuple contains (index, value). Loop as for i, val in enumerate(seq) to get both.

How do you loop through two lists at the same time?

Use zip(list1, list2). It pairs elements from both lists. Loop as for a, b in zip(list1, list2).

What is tuple unpacking in Python for loops?

Tuple unpacking is when Python automatically breaks a tuple into separate variables. In for x, y in pairs, each pair is a two-element tuple being unpacked into x and y.

Related Topics

Jasmine Massey
Jasmine Massey
Articles: 7