How does range() differ from enumerate()?

QuestionsQuestions8 SkillsProPython Control StructuresNov, 02 2025
093

The range() and enumerate() functions serve different purposes in Python:

range()

  • Purpose: Generates a sequence of numbers.
  • Usage: Commonly used in loops to iterate over a sequence of numbers.
  • Example:
    for i in range(5):
        print(i)
    This will output numbers from 0 to 4.

enumerate()

  • Purpose: Adds a counter to an iterable (like a list or a string) and returns it as an enumerate object.
  • Usage: Useful when you need both the index and the value of items in a loop.
  • Example:
    fruits = ["apple", "banana", "cherry"]
    for index, fruit in enumerate(fruits):
        print(index, fruit)
    This will output:
    0 apple
    1 banana
    2 cherry

Summary

  • Use range() when you need a sequence of numbers.
  • Use enumerate() when you need to iterate over an iterable and also keep track of the index.

0 Comments

no data
Be the first to share your comment!