Python is going to be hard

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Sep 4 04:11:15 CEST 2014


Seymore4Head wrote:

> Ok, I understand now that x is actually the first item in the list.
> What I want is a loop that goes from 1 to the total number of items in
> the list steve.

99% of the time, you don't want that at all. Trust me, iterating over the
values in the list is *nearly* always the right solution.

But for those times you actually do want 1...N, use the range() function.
Remember that in Python, ranges are "half open": the start value is
*included*, but the end value is *excluded*. Also, the start value defaults
to 0. So for example, if you wanted the numbers 1...5:

range(5) --> range(0, 5) --> [0, 1, 2, 3, 4]

range(1, 5+1) --> range(1, 6) --> [1, 2, 3, 4, 5]

So to iterate over 1 to the number of items in list `steve`:

for i in range(1, len(steve)+1):
    print(i)


But if you are ever tempted to write something like this:

for i in range(1, len(steve)+1):
    x = steve[i-i]  # adjust the index from 1-based to 0-based
    print(i, x)


we will take you out and slap you with a rather large hallibut
https://www.youtube.com/watch?v=IhJQp-q1Y1s

*wink*

The right way to do that is:

for i, x in enumerate(steve, 1):
    print(i, x)


-- 
Steven




More information about the Python-list mailing list