Home > OS >  Make a list of lists where the last value of list is incremented
Make a list of lists where the last value of list is incremented

Time:12-16

I want to make a list of lists where each sublist will have its second value greater than the second value of its predecessor. e.g. my list_of_lists = [[1, 1], [1, 2], [1, 3], [1, 4],...]

I thought this would do it but I can't see why it is not appending the correct current version of the list.

I would like to thank Scott and gionni for the work they put in helping me to understand why my attempt was wrong and the key role object references make in this.

Code

mylist = [1,1]
mylist_of_lists = []
for i in list(range(1,11,1)):
    print("i: ", i)
    mylist[1] = i
    print("mylist : ", mylist)
    mylist_of_lists.append(mylist)
    print("mylist_of_lists : ", mylist_of_lists)
print(mylist_of_lists)

Console return

i:  1
mylist :  [1, 1]
mylist_of_lists :  [[1, 1]]
i:  2
mylist :  [1, 2]
mylist_of_lists :  [[1, 2], [1, 2]]
i:  3
mylist :  [1, 3]
mylist_of_lists :  [[1, 3], [1, 3], [1, 3]]
i:  4
mylist :  [1, 4]
mylist_of_lists :  [[1, 4], [1, 4], [1, 4], [1, 4]]
i:  5
mylist :  [1, 5]
mylist_of_lists :  [[1, 5], [1, 5], [1, 5], [1, 5], [1, 5]]
i:  6
mylist :  [1, 6]
mylist_of_lists :  [[1, 6], [1, 6], [1, 6], [1, 6], [1, 6], [1, 6]]
i:  7
mylist :  [1, 7]
mylist_of_lists :  [[1, 7], [1, 7], [1, 7], [1, 7], [1, 7], [1, 7], [1, 7]]
i:  8
mylist :  [1, 8]
mylist_of_lists :  [[1, 8], [1, 8], [1, 8], [1, 8], [1, 8], [1, 8], [1, 8], [1, 8]]
i:  9
mylist :  [1, 9]
mylist_of_lists :  [[1, 9], [1, 9], [1, 9], [1, 9], [1, 9], [1, 9], [1, 9], [1, 9], [1, 9]]
i:  10
mylist :  [1, 10]
mylist_of_lists :  [[1, 10], [1, 10], [1, 10], [1, 10], [1, 10], [1, 10], [1, 10], [1, 10], [1, 10], [1, 10]]
[[1, 10], [1, 10], [1, 10], [1, 10], [1, 10], [1, 10], [1, 10], [1, 10], [1, 10], [1, 10]]

Desired output

my list_of_lists = [[1, 1], [1, 2], [1, 3], [1, 4],...]

CodePudding user response:

Occam's Razor: the reason they all look the same is that they all are the same.

You need to create a new list for each call to append to add (for example, append([mylist[0],i])).

  • Related