Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Loops Module 2 - Control Flow Python Python Basics Python Programming: From Zero to Real-World Applications

range() and enumerate() - Powerful Loop Tools

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • How range() works (start, stop, step)
  • How enumerate() gives index + value
  • Common patterns with both

range() - Generate Number Sequences

Terminalpython
range(5)          # 0, 1, 2, 3, 4
range(3, 8)       # 3, 4, 5, 6, 7
range(0, 10, 2)   # 0, 2, 4, 6, 8 (step=2)
range(10, 0, -1)  # 10, 9, 8, ..., 1 (countdown!)

# range() is lazy - does not create a list
# Convert to list to see values
print(list(range(5)))   # [0, 1, 2, 3, 4]
range() is lazy
range() does not create a list in memory. It generates numbers on demand. This is efficient for large ranges like range(1000000).

enumerate() - Index and Value Together

Terminalpython
fruits = ["apple", "banana", "cherry"]

# Without enumerate (clunky)
for i in range(len(fruits)):
    print(f"{i}: {fruits[i]}")

# With enumerate (Pythonic!)
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry

# Start from a custom index
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}: {fruit}")
# 1: apple, 2: banana, 3: cherry

Common Patterns

Terminalpython
# Countdown timer
for i in range(10, 0, -1):
    print(f"{i}...")
print("Launch!")

# Sum of 1 to 100
total = sum(range(1, 101))
print(total)   # 5050

# Every other element
for i in range(0, 10, 2):
    print(i)   # 0, 2, 4, 6, 8

Practical Exercise

Print 0 to 9 with range(10)
Print 10 to 1 (countdown) with range(10, 0, -1)
Use enumerate to print index: value of ['a', 'b', 'c']
Calculate sum(range(1, 101)) - what is the result?

Key Takeaways

  • range(stop): 0 to stop-1.
  • range(start, stop, step): custom sequences.
  • range() is lazy - efficient for large ranges.
  • enumerate() gives index + value - more Pythonic than range(len()).
  • enumerate(items, start=1) for 1-based indexing.
Previously: Lesson 13 covered break/continue.
Today: You learned: Master range() and enumerate() for cleaner loops.
Next: Lesson 15 covers nested loops.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments