3

I found something a bit weird when playing with lists. I usually use print() to debug or understand how things work but in this case the print() outputs are not helping me at all.

Here is a simple code, you will quickly see what I'm talking about:

a = [[]] * 5

b = [[]] * 5
b[0] = []
b[1] = []
b[2] = []
b[3] = []
b[4] = []

# It prints the same thing:
print(a)  # [[], [], [], [], []]
print(b)  # [[], [], [], [], []]

a[0] += ["test"]
b[0] += ["test"]

# Different results:
print(a)  # [['test'], ['test'], ['test'], ['test'], ['test']]
print(b)  # [['test'], [], [], [], []]

I was expecting a to behave like b, but it doesn't. Can someone explain this?

kdopen
  • 8,032
  • 7
  • 44
  • 52
Olivier Giniaux
  • 870
  • 2
  • 8
  • 22
  • can you add the output of the `print()` please. – maggick Jun 10 '15 at 13:56
  • 1
    *"I was expecting a to behave like b"* - why? In `b` you replace each element with a new, separate list, but in `a` they're still **references to the same list** (note: nothing in your question is a tuple). – jonrsharpe Jun 10 '15 at 13:59

0 Answers0