[Tutor] List indexing problem

Dave Kuhlman dkuhlman at rexx.com
Sat Jul 26 22:28:24 CEST 2008


On Sat, Jul 26, 2008 at 03:08:45AM -0400, Kent Johnson wrote:
> On Fri, Jul 25, 2008 at 7:35 PM, Mike Meisner <mikem at blazenetme.net> wrote:
> > Do you happen to know if there is an efficient way to initialize a  list
> > like this without explicitly writing out each element?
> 
> You can make a copy of the inner list each time through the loop:
>     IP = []
>     temp = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]
>     # initialize to zero
>     for i in range(20):
>         IP.append(list(temp))

How about::

    In [26]: IP = [[0, 0, 0] for x in range(5)]
    In [27]: IP
    Out[27]: [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
    In [28]: id(IP[0])
    Out[28]: 13122016
    In [29]: id(IP[1])
    Out[29]: 13121152
    In [30]: id(IP[2])
    Out[30]: 13121800

- Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list