initialising a list of lists

Daniel Dittmar daniel.dittmar at sap.corp
Wed Nov 16 09:08:50 EST 2005


Peter Kleiweg wrote:
> This does not what I want it to do:
> 
>     >>> a = [[]] * 6
>     >>> a[3].append('X')
>     >>> a
>     [['X'], ['X'], ['X'], ['X'], ['X'], ['X']]
> 
> This does what I want:
> 
>     >>> b = [[] for _ in range(6)]
>     >>> b[3].append('X')
>     >>> b
>     [[], [], [], ['X'], [], []]
> 
> The first is clear and wrong. The second is hairy and right.

> Is there a way to do it clear 

Define a function:

import copy

def init_list (count, element):
     return [copy.copy (element) for i in xrange (count)]

> and right?

Test it.

Daniel




More information about the Python-list mailing list