Vermillion Vermillion - 1 month ago 8
Python Question

Using enumerate in Python to iterate up to len(list) - 1

If I have a list

A = [5, 2, 7, 4, 6, 1, 3, 2, 6, 19, 2, 6]


I can loop through all the elements but the last, using this code:

for i in range(len(A) - 1):
pass


Can I use
enumerate()
in this loop to accomplish the same thing?

Answer

Slice the list you provide to enumerate to achieve a similar effect:

for i, item in enumerate(A[:-1]):
    print(item, end=' ')

touches all, but the last, elements of the list A.

Comments