⚡0 XP🔥0

for Loop and range()

Lesson 11 of 33 ⏱ 5 min read ✎ 4 exercises ❓ 6-question quiz ▶ Runs Python

Loop over strings, lists and ranges with for, use range(start, stop, step), enumerate(), zip(), nested loops and pattern printing.

The for loop#

A for loop goes through the items of a sequence (string, list, tuple, range...) one by one. You don't manage a counter yourself.

for variable in sequence:
    # body runs once for each item
▶ Try it YourselfPython
Ctrl + Enter to run

In each round (called an iteration), the loop variable fruit holds the next item: first "apple", then "mango", then "banana".

Looping over a string#

A string is a sequence of characters:

▶ Try it YourselfPython
Ctrl + Enter to run

The range() function#

range() generates a sequence of numbers - perfect for "repeat N times".

Form Meaning Example Numbers produced
range(stop) 0 up to stop-1 range(5) 0 1 2 3 4
range(start, stop) start up to stop-1 range(2, 6) 2 3 4 5
range(start, stop, step) jump by step range(1, 10, 2) 1 3 5 7 9
negative step count down range(5, 0, -1) 5 4 3 2 1
▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

range() की सबसे ज़रूरी बात: आखिरी संख्या (stop) शामिल नहीं होती।

  • range(5) → 0, 1, 2, 3, 4 (5 नहीं आता)
  • range(1, 11) → 1 से 10 तक (11 नहीं आता)

इसलिए 1 से n तक चलाना हो तो range(1, n + 1) लिखें। तीसरा number step है - यानी हर बार कितना बढ़ाना (या घटाना) है।

Repeat something N times#

▶ Try it YourselfPython
Ctrl + Enter to run

Sum of 1 to N#

▶ Try it YourselfPython
Ctrl + Enter to run

for vs while#

for loop while loop
You know how many times / you have a sequence You repeat until a condition changes
Counter is automatic You manage the counter
for i in range(10): while balance > 0:
Cannot accidentally go infinite (over a range) Can become infinite if you forget the update

enumerate() - index and value together#

Often you need the position as well as the item:

▶ Try it YourselfPython
Ctrl + Enter to run

zip() - loop over two lists together#

▶ Try it YourselfPython
Ctrl + Enter to run

zip() stops at the shortest list.

Nested loops#

A loop inside another loop. The inner loop completes all its rounds for each round of the outer loop.

▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

Nested loop में अंदर वाला loop (inner) हर बार पूरा चलता है, फिर बाहर वाला (outer) loop एक कदम आगे बढ़ता है। जैसे घड़ी में minute की सुई पूरा चक्कर लगाती है, तब hour की सुई एक आगे बढ़ती है।

ऊपर के example में outer loop 3 बार और inner loop हर बार 3 बार चलता है, यानी कुल 3 × 3 = 9 बार print होता है।

Pattern printing#

Patterns are a great way to understand nested loops:

▶ Try it YourselfPython
Ctrl + Enter to run

for...else#

Like while, a for loop can have else, which runs when the loop finishes without break:

▶ Try it YourselfPython
Ctrl + Enter to run

Don't modify a list while looping over it#

Common Mistake

Removing items from a list while looping over the same list skips items:

nums = [1, 2, 2, 3]
for n in nums:
    if n == 2:
        nums.remove(n)
print(nums)     # [1, 2, 3]  - one 2 was skipped!

Loop over a copy instead (for n in nums[:]:) or build a new list (you'll learn list comprehensions later).

Summary#

  • for item in sequence: visits every item of a string, list, tuple, range, etc.
  • range(start, stop, step) - stop is excluded; use range(1, n + 1) for 1..n.
  • enumerate() gives index + value; zip() walks several lists together.
  • Nested loops: the inner loop runs fully for each outer iteration.
  • for...else: else runs only if the loop wasn't broken.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Multiplication table

Read a number n and print its table from 1 to 10 in the format n x i = result. For 7:

7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70
Test input:
7
Expected output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
2

Sum of even numbers

Read n and print the sum of all even numbers from 1 to n (inclusive). Use range() with a step.

Test input:
10
Expected output:
30
3

Count vowels

Read a word or sentence and print how many vowels (a, e, i, o, u - upper or lower case) it contains.

Test input:
Vindhya Education
Expected output:
7
4

Star triangle

Read n and print a right-angled triangle of stars. For n = 4:

*
**
***
****
Test input:
4
Expected output:
*
**
***
****

Quick Quiz

Q1.

What does range(5) produce?

Q2.

What does list(range(2, 11, 3)) give?

Q3.

How do you loop from 10 down to 1?

Q4.

What is printed?

for ch in "abc":
    print(ch, end="")
Q5.

How many times does print run?

for i in range(3):
    for j in range(4):
        print(i, j)
Q6.

What does enumerate(["a", "b"]) give in a for loop?