1

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
Python - Using the Multiply Operator to Create Copies of Objects in Lists

Python behaves unexpected when i append to a list, which is in another list. Here's an example:

>>> _list = [[]] * 7
>>> _list
[[], [], [], [], [], [], []]
>>> _list[0].append("value")

What i expect:

>>> _list
[['value'], [], [], [], [], [], []]

What i get:

>>> _list
[['value'], ['value'], ['value'], ['value'], ['value'], ['value'], ['value']]

Why is this? how can i go around it?

Community
  • 1
  • 1
ToonAlfrink
  • 2,501
  • 2
  • 19
  • 19
  • 1
    also: [Python - Dynamic Nested List](http://stackoverflow.com/questions/3587215/python-dynamic-nested-list?rq=1) – sloth Dec 07 '12 at 12:36
  • @Jacob I don't see a default argument here... it is a similiar effect, but not the same. – glglgl Dec 07 '12 at 12:38

1 Answers1

4

Your problem is that your list does not contain seven independent lists, but rather the same list seven times.

To create a list of list, better use a list comprehension:

_list = [[] for _ in xrange(7)]

which will result in a list containing seven different lists.

sloth
  • 99,095
  • 21
  • 171
  • 219