The enumerate() function in Python

Overview:

  • Given an iterable, the built-in function enumerate() returns an iterator which returns an index and the element from the iterable as a tuple upon each call to the __next__().

  • The index is zero based. The index can be modified to start with a non-zero value by passing in the required starting index value to the start parameter of the enumerate() function.

Example:

# Example Python program that creates an enumerate
# object from an iterable and prints the contents
# with an index
playArea = ["Slide", "Swing", "Seesaw", "Spring rider"]

# Start with index 1
playEnum = enumerate(playArea, 1)

try:
    # Will print indices 1 and 2
    print(playEnum.__next__())
    print(playEnum.__next__())

    # Will print indices 3 and 4
    for i in playEnum:
        print(i)

except StopIteration:
    print("Nothing to print")

Output:

(1, 'Slide')
(2, 'Swing')
(3, 'Seesaw')
(4, 'Spring rider')

 


Copyright 2024 © pythontic.com