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