0

Consider this code:

lst = [['a']*5]*4
lst[1][1] = '*'

And this code:

lst= [['a'] * 5 for i in range(4)]
lst[1][1] = '*'

What makes them different?

Thanks

Daniel Gagnon
  • 199
  • 1
  • 6
  • Also possible duplicate of [Python List Problem](http://stackoverflow.com/questions/1959744/python-list-problem) – Mp0int Dec 07 '13 at 14:11

2 Answers2

2

Those are the same objects:

>>> lst = [['a']*2]*2
>>> map(id, lst)
[60543624, 60543624]
>>> lst[0] is lst[1]
True
alko
  • 46,136
  • 12
  • 94
  • 102
1

Because, you are not creating four lists with 5 as in them. Instead, you are creating 4 lists which point to the same list with 5 as in it. So, you change one, the effect is seen in all others as well.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497