Home/Learn/Python A–Z/Loops — for, while, range, enumerate & zip

Loops — for, while, range, enumerate & zip

Beginner
Control Flow

Python's for loop iterates over ANY iterable directly — no index bookkeeping. range generates number sequences; enumerate gives index+value; zip walks multiple sequences together.

Overview

Coming from Java, the biggest shift: Python's for is a for-each. You loop over the items themselves, and when you need indexes you ask for them with enumerate() — writing for i in range(len(items)) to then do items[i] is the #1 sign of a Java developer writing Python. while handles condition-driven loops. These iteration tools (range, enumerate, zip, reversed, sorted) are the vocabulary of every Python DSA solution.

for-each, range & enumerate

range(start, stop, step) is lazy — it generates values on demand (constant memory even for range(10**9)). enumerate(iterable, start=) yields (index, value) pairs — the idiomatic way to get positions.

for-each first; enumerate when you need the index
skills = ["java", "python", "sql"]

for skill in skills:              # items directly — no index
    print(skill)

for i, skill in enumerate(skills, start=1):
    print(f"{i}. {skill}")        # 1. java  2. python  3. sql

print(list(range(5)))             # [0, 1, 2, 3, 4]
print(list(range(2, 11, 2)))      # [2, 4, 6, 8, 10]
print(list(range(5, 0, -1)))      # [5, 4, 3, 2, 1] — countdown

# Classic index loop — only when you MUST mutate by index
nums = [3, 1, 4]
for i in range(len(nums)):
    nums[i] *= 10

zip, while & Looping Dicts

zip pairs elements from multiple iterables and stops at the shortest. Dict iteration: loop keys by default, .items() for key+value. while runs until its condition is falsy — remember to make progress or you loop forever.

zip for parallel iteration; while for conditions
names  = ["Asha", "Vikram", "Neha"]
scores = [88, 92, 79]

for name, score in zip(names, scores):
    print(f"{name}: {score}")

marks = {"dsa": 85, "java": 90}
for subject, mark in marks.items():
    print(subject, mark)

# while — condition-driven (e.g. binary search skeleton)
lo, hi = 0, 100
while lo <= hi:
    mid = (lo + hi) // 2
    if mid == 42:
        break
    elif mid < 42:
        lo = mid + 1
    else:
        hi = mid - 1
print("found at", mid)

Key Points to Remember

  • 1for iterates values directly; enumerate() when you need indexes — avoid range(len(x)) + indexing
  • 2range is lazy (constant memory); range(n, -1, -1) counts down
  • 3zip stops at the shortest input; use itertools.zip_longest to pad
  • 4Dict loops: "for k in d", "for k, v in d.items()"

Interview Questions

Sign in to ask Aria
1

How do you get both index and value while looping a list pythonically?

EasyCapgemini
2

Why is range(10**9) memory-safe in Python 3? What does range actually return?

MediumGoogle
3

What does zip do when the inputs have different lengths?

EasyPhonePe

Ask Aria about Loops — for, while, range, enumerate & zip

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…