0

I wonder why append add a number to every list that I have in my list. Not only to that one ([0]) that I have choosen. What's the difference between writing [0] or any other number next to append?

j = [[]] * 5 
j[0].append(5) # add 5 to every list on list
j[1].append(4) # what's the diffrence? [1] or [0]; it adds number to every element anyway
print (j)
j.append(0) # add 0 to the main list
print (j)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Pal Kol
  • 75
  • 2
  • 6

2 Answers2

1

There is no difference.

j = [[]] * 5

Repeats the same empty list instance five times, once at each index.

IOW, the initial empty list is referenced 5 times.

You could verify this:

id(j[0]) == id(j[1])

To instantiate a different empty list at each index requires a comprehension:

[[] for _ in range(5)]

John
  • 6,433
  • 7
  • 47
  • 82
1

This happens because your initial list j contains 5 references to the same object (so 5 copies to the same list). That's why everything you append goes to every list.

Instead, if you actually create 5 different sublists:

j = [[] for _ in range(5)]

Then it will work as you expect:

[[5], [4], [], [], [], 0]

carrdelling
  • 1,675
  • 1
  • 17
  • 17