0

I do not have much experience in Python. All I want to do is to insert elements in nested lists.I have two lists which seems to be similar but their behaviour is completely different.

list1 = [['a','b']] * 3 list2 = [['a','b'],['a','b'],['a','b']]

When I output print these two lists both give same output: [['a', 'b'], ['a', 'b'], ['a', 'b']]

But when I try to insert elements in nested lists both do that in a different way. Below is the code for inserting elements in nested list.

list1 = [['a','b']] * 3
for item in list1:
  item.append("Hello")
print (list1)

This outputs

[['a', 'b', 'Hello', 'Hello', 'Hello'], ['a', 'b', 'Hello', 'Hello', 'Hello'], ['a', 'b', 'Hello', 'Hello', 'Hello']]

While when I define list in the following way it does exactly what I want.

list2 = [['a','b'],['a','b'],['a','b']]
for item in list2:
  item.append("Hello")
print (list2)

This gives following output: [['a', 'b', 'Hello'], ['a', 'b', 'Hello'], ['a', 'b', 'Hello']].

Why are these two behaving differently? list1 = [['a','b']] * 3 list2 = [['a','b'],['a','b'],['a','b']] Screenshot of Program output

2 Answers2

2

When you use the * operator here, you are saying "I want 3 of these".

So you're getting 3 references to the same ['a', 'b']. In your case, you're adding 'Hello' to that same ['a', 'b'] reference.

List of lists changes reflected across sublists unexpectedly

If you want to make 3 separate references, try using list comprehension:

>>> x = [['a', 'b'] for i in range(0, 3)]
>>> x
[['a', 'b'], ['a', 'b'], ['a', 'b']]
>>> x[0].append('Hello')
>>> x
[['a', 'b', 'Hello'], ['a', 'b'], ['a', 'b']]
pythomatic
  • 647
  • 4
  • 13
2
list1 = [['a', 'b']] * 3

This creates a list of lists, as you know. However, the nested lists are actually all references to the same list object.

So when you iterate over list1 with

for item in list1:

item refers to the same list object on each iteration. So you repeated append to the same list.

On the other hand, list2 in your example code is explicitly assigned a list with three different lists. Those lists happen to have the same elements, but they are distinct lists.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268