This question has already been answered:

item = 5 for i in range(item): item -= 1 print(i, range(item), item) 

I'm confused about something, how is it that when range (0, 1) i = 3 and in general, what is happening here and how does it work? Why i reaches the end, although item is decreasing, shouldn't it be finished earlier.

Please explain in more detail, thanks in advance for the answer to my stupid question.

Marked as a duplicate by the participants Viktorov , Avernial , 0xdb , LFC , aleksandr barakin on March 31 at 16:42 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    Please attach the code not with a screenshot, but with a code. править button - gil9red
  • In the second version there will be a slightly different result, because range() does not work that way there. - Enikeyschik

2 answers 2

range is called only once. This function returns an iterable range object.
for i in range(item): in this case is equivalent to for i in [0,1,2,3,4]: i.e. range not called for each iteration, only once and then the cycle runs through the elements of this collection.

    In 2.xx range returns list. In 3.xx, everything is much better - there is a range of behavior similar to xrange in 2.xx, and xrange itself is completely removed. xrange is in some sense the progenitor of generators, it does not store the entire list in memory, but each time it calculates the current element.