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:
This will output numbers from 0 to 4.for i in range(5): print(i)
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:
This will output:fruits = ["apple", "banana", "cherry"] for index, fruit in enumerate(fruits): print(index, fruit)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.
