Home > front end >  python range and for loop understanding
python range and for loop understanding

Time:03-26

I am new to python / coding and looking to understanding the range function more and how it is used in conjunction with the "for" loop.

So I know that the range function takes in 3 parameters: range(start, stop, step). For the below function, I passed in my array called test_numbers, then created a "for" loop where "i" starts counting from len(list_of_numbers)-1 (to give me the index values)

I was expecting the result for "i" to print 0,1,2,3,4,5 but it only printed 5 for "i". I am wondering why is that? If I put 6 as the "stop" argument, would it not just print from range start of the length of the array as in [0,1,2,3,4,5] all the way then stop before 6? that is my confusion. Any help /explanation would be great!

test_numbers = [1,2,4,5,6]

def testRange(list_of_numbers):
    for i in range(len(list_of_numbers), 6):
        print(i)

testRange(test_numbers)

The result: 5

Was expecting: 0,1,2,3,4,5

CodePudding user response:

When you call range() with two arguments, the first argument is the starting number, and the second argument is the end (non-inclusive). So you're starting from len(list_of_numbers), which is 5, and you're ending at 6. So it just prints 5.

To get the results you want, the starting number should be 0, and the end should be len(list_of_numbers) 1. If you call it with one argument, that's the end, and 0 is the default start. So use

for i in range(len(list_of_numbers) 1):

or if you want to pass the start explicitly:

for i in range(0, len(list_of_numbers) 1):

CodePudding user response:

range stop parameter is exclusive and start is inclusive - if you provided len result (of 5) and 6 as the stop then the range result will contain only one element [5]

If you'd like to have 0..6 you should use

range(0, 6)

or, what you probably want to do to iterate over all array indices

range(0, len (list_of_numbers))

CodePudding user response:

range gives you and iterator between (start, end) end not included. So in your case the iterator is (start=len(list_of_numbers), end=6). Since len(list_of_numbers) = 5, this translates to range(5,6) which is 1 element, 5, since 6 is excluded. https://docs.python.org/3/library/functions.html#func-range

  • Related