Creating a List of Empty Lists

Samuel Tardieu sam at rfc1149.net
Thu Dec 4 16:28:37 EST 2003


>>>>> "Anton" == Anton Vredegoor <anton at vredegoor.doge.nl> writes:

Anton> Why is "Smith" copied to all elements in the matrix?

:)

The construct

  [[]] * n

gives you a list with n references to the same list. When you modify
one of the elements, all the references will see the changes.

You can use one of the three (there are more)

  ([[]]*n)[:]
  [[] for _ in range(n)]
  map (lambda _: [], range(n))

to get n different copies of [].

 Sam
-- 
Samuel Tardieu -- sam at rfc1149.net -- http://www.rfc1149.net/sam




More information about the Python-list mailing list