'What is the pythonic way to print a list of numbers over the length of the list?

fruits = ["apple", "orange", "banana"]

for i in range(len(fruits)):
    print(i+1)

# output: 1 2 3

Is there a better way of doing this rather than range(len()) ?



Solution 1:[1]

Use the enumerate built-in fuction:

fruits = ["apple", "orange", "banana"]

for i, _ in enumerate(fruits, 1): # _ is used in python for non used vars
    print(i)

# output: 1 2 3

Otherwhise, if you use range you should use range(1,len(fruits)+1) to avoid the +1 inside the loop

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1