+ 3
python Can anyone Explain this
Can anyone Explain this:- list1 = [[]] * 3 print(list1) list1[1].append(5) print(list1) OP:- [[5],[5],[5]]
6 ответов
+ 4
The reason why the result is [[5], [5], [5]] lies in the way the list list1 is created and how the assignment is performed.
In the line list1 = [[]] * 3, a list with three empty sublists is created. Note that all sublists share the same reference. This means that they essentially represent the same object.
When you call list1[1].append(5), you are adding the element 5 to the second sublist. Since all sublists share the same reference, you are effectively modifying all the sublists in list1.
To avoid this behavior, you can initialize the list using a loop and create individual sublists instead of using multiplication.
+ 4
I wouldn't have expected that behavior, and it seems weird, but it's evidently creating a list of 3 references to the same sub-list when you initialize it that way.
+ 2
Thanks jan Markus I understand now
Thanks bob_Li
+ 1
@Orin Cook, Thanks for reply
pardon me but i,m not able to get ans or explanation not able to understand the ans if i do list1=[[]]*3 its will get ans
[[],[],[]]
and If i do append list1[1].append(5) and I get the op [[5],[5],[5]]
+ 1
Amol Bhandekar
The way you create the list is important.
list1 = [[]] *3
and
list1 = [[], [], []]
are not the same. Even though if you print them, they LOOK the same, they are fundamentally different.
In the first one, the inner lists is referring to the same object. altering one alters all others.
The second one have lists independent of each other.
0
Amol Bhandekar
try this:
list1 =[[]]* 3
print(list1)
list1[2].append(5)
print(list1[0] is list1[1] is list1[2])
print(list1)
list2 =[[], [], []]
print(list2)
list2[2].append(5)
print(list2[0] is list2[1] is list2[2])
print(list2)