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)
[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.
range() function yields values which start from
default. This matches the use of indices, which also count from
Cameron Simpson firstname.lastname@example.org
range(5) produces a sequence of 5 integers starting with
By providing the parameter
5 you’re saying: give me 5 numbers, starting from
0 and stopping when you get to
To append the numbers 1 to 5 you’d do this:
my_list = 
for i in range(1, 6):
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.
Oh, starts from 0. I may have confused it again. Thank you for the reply!
Thank you for the reply. I get it now.
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)]