1

Folks, Basically what I am expecting is a list of lists based on the input comma separated numbers. As you can see I have 5,6 which means I need to create a 5 lists with 6 elements and each of the element in the lists will have to be multiplied by the index position. So what I need from the below input is [[0,0,0,0,0,0], [0,1,2,3,4,5], [0,2,4,6,8,10], [0,3,6,9,12,15],[0,4,8,12,16,20]]

instead what I get is [[0, 4, 8, 12, 16, 20], [0, 4, 8, 12, 16, 20], [0, 4, 8, 12, 16, 20], [0, 4, 8, 12, 16, 20], [0, 4, 8, 12, 16, 20]]

not sure what I am doing wrong.. Can anyone please help?

    input_str = '5,6'
    lst = list(input_str.split(","))
    main_lst = []
    total_list = int(lst[0])
    total_elements = int(lst[1])
    lst1 = []
        for i in range(total_list):
            lst1.clear()
            for j in range(total_elements):
                lst1.append(j*i)
        print(lst1)
        main_lst[i] = lst1
    print(main_lst)
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – John Coleman Jun 16 '21 at 03:47

2 Answers2

2

This can easily be done using list comprehension

lstCount,elementCount = map(int,'5,6'.split(','))
bigLst = [[i*j for j in range(elementCount)] for i in range(lstCount)]

output

[[0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5], [0, 2, 4, 6, 8, 10], [0, 3, 6, 9, 12, 15], [0, 4, 8, 12, 16, 20]]
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
0

You should append lst1's copy, not assign to it.Or the value in main_lst will change when you change lst1's value.

code:

input_str = '5,6'
lst = list(input_str.split(","))
main_lst = []
total_list = int(lst[0])
total_elements = int(lst[1])
lst1 = []
for i in range(total_list):
    lst1.clear()
    for j in range(total_elements):
        lst1.append(j*i)
    print(lst1)
    main_lst.append(lst1.copy())#you should append its copy
print(main_lst)

result:

[0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5]
[0, 2, 4, 6, 8, 10]
[0, 3, 6, 9, 12, 15]
[0, 4, 8, 12, 16, 20]
[[0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5], [0, 2, 4, 6, 8, 10], [0, 3, 6, 9, 12, 15], [0, 4, 8, 12, 16, 20]]
leaf_yakitori
  • 2,232
  • 1
  • 9
  • 21