Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make a list of lists where the last value of list is incremented

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.

Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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],…]

>Solution :

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])).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading