Home > database >  List iteration in python with [0]*n
List iteration in python with [0]*n

Time:01-12

I am not getting this. Why the output is coming [0,0,10,20,30] for the below code snippet.

my_list=[0]*5
for i in range(1,5):
    my_list[i]=(i-1)*10
print(my_list)

CodePudding user response:

In python index starts at 0, here you have to use range(0,5) to take this into account:

my_list=[0]*5
for i in range(0,5):
    my_list[i]=(i-1)*10
print(my_list)

as to fill your vector properly.

CodePudding user response:

List indexing starts at zero and the 2nd parameter of range is a stop value (i.e. 5 is not included), so you can break down the process in your mind (or on paper):

                               # my_list          i      (i-1)*10
my_list=[0]*5                  # [0, 0, 0, 0, 0]
for i in range(1,5):           #                  1..4
    my_list[i]=(i-1)*10        # [0,00, 0, 0, 0]  1      00
                               # [0, 0,10, 0, 0]  2      10
                               # [0, 0,10,20, 0]  3      20
                               # [0, 0,10,20,30]  4      30  
print(my_list)

If you are looking to obtain [0,10,20,30,40] you have to think in terms of zero-based indexing:

my_list = [0]*5
for i in range(5):      # 0..4   range(5) is the same as range(0,5)
    my_list[i] = i*10 
  •  Tags:  
  • Related