+ 1

Why does first list has one less element in the same range?

https://www.sololearn.com/en/compiler-playground/caT4cbimkq5J

7th May 2024, 10:03 AM
Igor Matić
Igor Matić - avatar
7 Antworten
+ 5
It is because: range(15), if put it into a list, becomes [0, 1, 2, ... 14] # 15 elements range(1, 15), if put it into a list, becomes [1, 2, 3, ... 14] # 14 elements
7th May 2024, 1:03 PM
Wong Hei Ming
Wong Hei Ming - avatar
+ 7
Igor Matić , as Wong Hei Ming already said, but with other words: > if we use only 1 argument with range() function, this argument is seen as the upper bound, the lower bound is 0 by default. > if we use 2 arguments, lower and upper bounds are like the arguments given. > in both cases the upper bound itself is *not* included in the result. so if we need numbers from 0 upto and including 10 we have to do it like: print(list(range(0, 10 +1))) or: print(list(range(10 +1)))
7th May 2024, 2:44 PM
Lothar
Lothar - avatar
+ 5
Wong Hei Ming , thanks for your great explanation! very well done!
8th May 2024, 6:38 PM
Lothar
Lothar - avatar
+ 3
A little something add to Lothar's answer. > if we use 3 arguments, you can increase / decrease the next value by more than 1 print(list(range(1, 15, 3))) # [1, 4, 7, 10, 13] print(list(range(15, 1, -3))) # [15, 12, 9, 6, 3] So, the range function can be rewritten as: range(start=0 (optional), end (required), step (optional)) When you type range(15), it is translated into range(0, 15). The first number is 0 and end at 15 (exclusive). If you type range(1, 15), the first number is 1, and end at 15 (exclusive).
7th May 2024, 2:58 PM
Wong Hei Ming
Wong Hei Ming - avatar
+ 2
Igor Matić Short answer: yes Medium answer: why not trying it in playground? Long answer: remember range(start, end, step). If we want a descending order, the start must be the higher end, and end is the lower end. If you type: # thinking like: yeah, we start from 15, end at 1, and the step size is 3 print(list(range(15, 1, 3))) what you get: [] # an empty list It is because the stepping is a positive number. We start from 15, step is positive 3 so the next number is 18. However the end is 1, so it must be descending. Which mean the next number must be smaller than 15. So you can think range() function works like this: From the "start", we ADD the "step" until reaching the "end". So in the previous answer: print(list(range(15, 1, -3))) The first number: 15 The second number: 15 + (-3) = 12 The third number: 12 + (-3) = 9 And so on...
8th May 2024, 4:36 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 1
Thank you!
7th May 2024, 1:33 PM
Igor Matić
Igor Matić - avatar
+ 1
Wong Hei Ming , for ranges in descending order, arguments must be reversed (from big to small number) and stepping needs to be a negative number?
7th May 2024, 8:53 PM
Igor Matić
Igor Matić - avatar