Vermillion Vermillion - 1 year ago 68
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):

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download