Vermillion
Vermillion

Reputation: 1308

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?

Upvotes: 7

Views: 3587

Answers (2)

Julien Spronck
Julien Spronck

Reputation: 15433

Of course:

for i, item in enumerate(A[:-1]):
    pass

Upvotes: 1

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160577

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.

Upvotes: 9

Related Questions