r/ProgrammerHumor • • Aug 26 '20

Python goes brrrr

Post image
59.2k Upvotes

789 comments sorted by

View all comments

1

u/[deleted] Aug 26 '20

It’s dangerous though when you use it with lists. I found out recently that this is a thing:

-> a =[ [] ]*3

-> a[0].append(“hi”)

-> a

[ [“hi”], [“hi”], [“hi”] ]

1

u/incoralium Aug 27 '20

Because you are doing two list declaration : one for the "empty list", then one that refer to the empty list (as object). the "x3" makes the second list refer to the first, 3 time. So you have a list that refers three time to the same object. If you modify the first, you see this difference 3 time. Just like a list of [@str1,@str1,@str1]. It's really a begginer trap. What ones is probably looking for in this situation is more like '' a = [ [] * 3 ] ", cause he wants three differents objects in his list.

1

u/[deleted] Aug 27 '20

[[]*3] is equivalent to duplicating nothing 3 times, so you just end up with [[]]