Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • use all range forms confidently
  • handle reverse loops with negative step
  • iterate without range over strings/lists
  • avoid off-by-one loop errors

range behavior recap

list(range(5))         # [0, 1, 2, 3, 4]
list(range(2, 6))      # [2, 3, 4, 5]
list(range(2, 10, 3))  # [2, 5, 8]

Negative step examples

list(range(10, 0, -2))  # [10, 8, 6, 4, 2]
list(range(5, -1, -1))  # [5, 4, 3, 2, 1, 0]
Trap:
list(range(1, 10, -1))  # []
Reason: step direction does not match start/stop relation.

for loop without range

String traversal

for ch in "hello":
    print(ch)

List traversal

nums = [10, 20, 30]
for x in nums:
    print(x)

Dictionary traversal

d = {"a": 1, "b": 2}
for k in d:
    print(k, d[k])

Index + value using enumerate

fruits = ["apple", "mango", "kiwi"]
for i, fruit in enumerate(fruits):
    print(i, fruit)

Exam hints and traps

  • stop value in range is excluded
  • wrong sign in step can produce empty iteration
  • direct iteration gives values, not indexes

Practice

  1. Print indexes and characters for "python".
  2. Reverse-print list [3, 5, 7, 9] using range indexes.
  3. Predict output:
for i in range(3, 3):
    print(i)

Answers

for i, ch in enumerate("python"):
    print(i, ch)
  1. No output.