0

I have a list of lists, with identical elements, created like this:

list1=[1,2,3]
list2=[]
for i in range(6):
    list2.append(list1)
list2

The outcome is:

[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

I want to be able to change the elements of the nested list; for example:

list2[0][0]=4
list2

produces:

[[4, 2, 3], [4, 2, 3], [4, 2, 3], [4, 2, 3], [4, 2, 3], [4, 2, 3]]

But I only want to change the first element of the first list:

[[4, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

How can I do this ? What am I missing in the iterating process ? At the end, I want to be able to reference any element in list1

glibdud
  • 7,550
  • 4
  • 27
  • 37
horace_vr
  • 3,026
  • 6
  • 26
  • 48
  • @gibdud Indeed, the underlying problem was the same, but searching for my question did not find the duplicate one; and I think the two answers provided are simpler and slicker than the ones provided in the other question. – horace_vr May 06 '19 at 12:57

2 Answers2

1

The easiest way from your code is:

for i in range(6):
    list2.append(list1[:])

[:] does copy operation on list, so it's not the same list that you append everytime but a copy.

Austin
  • 25,759
  • 4
  • 25
  • 48
1
list2 = [[1,2,3] for i in range(6)]
list2[0][0]=4
print (list2)

output:

[[4, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
ncica
  • 7,015
  • 1
  • 15
  • 37
  • Was it really necessary to add a second answer to a duplicate question? – glibdud May 06 '19 at 12:46
  • 1
    you are copying list1 in all items of list2 .and you have that list[0], list[1], list[2] are pointed on the same list (list1) – ncica May 06 '19 at 12:51
  • I was obviously too fast and I did not notice it as a duplicate @glibdud – ncica May 06 '19 at 12:53
  • @ncica your answer is correct and is working, but I will accept Austin's because is more in line with my code (list1 is an existing list) – horace_vr May 06 '19 at 12:59