I know this is a simple code, but somehow I kind of wonder why it is so…
my_list = [ ]
for i in range (5):
my_list.append (i + 1)
print(my_list)
[1, 2, 3, 4, 5]
I was thinking of [2,3,4,5,6]. Because it is i+1 for each number from 1 to 5…
Thank you in advance for the explanation.
cameron
(Cameron Simpson)
2
The range()
function yields values which start from 0
, not 1
, by
default. This matches the use of indices, which also count from 0
.
Try this:
print(list(range(5)))
Cheers,
Cameron Simpson cs@cskk.id.au
1 Like
jhanarato
(Ajahn Jhanarato)
3
range(5)
produces a sequence of 5 integers starting with 0
, not 1
By providing the parameter 5
you’re saying: give me 5 numbers, starting from 0
and stopping when you get to 5
.
To append the numbers 1 to 5 you’d do this:
my_list = []
for i in range(1, 6):
my_list.append(i)
print(my_list)
This way the range gives you all the numbers from start to stop, but does not include stop. This is called a “half open range” in computing.
1 Like
Oh, starts from 0. I may have confused it again. Thank you for the reply!
Thank you for the reply. I get it now.
jhanarato
(Ajahn Jhanarato)
7
These are also equivalent:
# Convert an iterable to a list
my_list = list(range(1, 6))
# Use a list comprehension
my_list = [i for i in range(1, 6)]
1 Like