-2

i create à list (of lists) with pre-defined length.

i then fill this list using a for loop

at the end, each item of the list should be different, but in reality they are all the same (the last value given in the for loop)

i have to add a small "initialisation loop" in order to get the expected result

Ok, it works but i don't understand this behaviour, is there anybody who can explain me what i missed ?

list_of_list = 4*[3*[0]]
liste1 = list_of_list
print('liste1: ', liste1)


# i have to un-comment the following lines
# if i want the program to give the expected result
'''
for y in range(4):
    list_of_list[y] = [0, 0, 0]
liste2 = list_of_list
print('liste2: ', liste2)
'''





    
for k in range(4):
    list_of_list[k][0] = k
    list_of_list[k][1] = 2*k
    list_of_list[k][2] = 3*k
    print('list_of_list[k]= ', list_of_list[k])

    
print('list_of_list= ', list_of_list)
    

1 Answers1

0

If your expected output is

[[0, 0, 0], [1, 2, 3], [2, 4, 6], [3, 6, 9]]

Then you can acheive this with a list comprehension

[[k*(i+1) for i in range(3)] for k in range(4)]
mama
  • 2,046
  • 1
  • 7
  • 24