Fwd: Re: [Tutor] Issues with initializing lists
by steve other posts by this author
Aug 10 2001 2:41PM messages near this date
RE: [Tutor] Hashing [And why hash() NEVER returns -1]
|
[Tutor] Object Oriented References? and a couple of questions <--LONG
Hi there,
I don't know why what you said is happening, is happening...!! It looks
mighty strange, though with list comprehensions you can get what you want...
code:
============================================================
> >> l = [ [None]*3 for x in range(0,4) ]
> >> l
[[None, None, None], [None, None, None], [None, None, None], [None, None,
None]]
> >> l[1][1] = 'foo'
> >> l
[[None, None, None], [None, 'foo', None], [None, None, None], [None, None,
None]]
===============================================================
hope that helps....and hope some of the gurus explain this deep mystery soon
...:)
Peace
Steve
> Hi,
> I am a bit confused about the usage of lists in Python. For an application
> I am writing, I would like to create a list of lists with some default
> values, and then fill in certain items in the list later.
>
> As an example:
> >>> l1=[[None]*3]*4
> >>> l1
>
> [[None, None, None], [None, None, None], [None, None, None], [None, None,
> None]]
>
> Now, suppose I want to fill in the second item in the second sublist. I try
>
> >>> l1[1][1]='hello'
>
> Then 'l1' looks like
>
> >>> l1
>
> [[None, 'hello', None], [None, 'hello', None], [None, 'hello', None],
> [None, 'hello', None]]
>
> Note how 'hello' has propagated to each sublist.
>
> Why is this?
>
>
> I could do
>
> l1=[]
>
> >>> for i in range(4):
>
> ... l1.append([])
> ... for j in range(3):
> ... l1[i].append(None)
> ...
> l1[1][1]='hello'
>
> >>> l1
>
> [[None, None, None], [None, 'hello', None], [None, None, None], [None,
> None, None]]
>
> This looks fine. But this approach really seems excessive.
>
> My real question is how do I conveniently initialize such a list so that I
> can later fill in the sublists?
-----------------------------------------
bug, n:
A son of a glitch.
-----------------------------------------
-------------------------------------------------------
--
-----------------------------------------
bug, n:
A son of a glitch.
-----------------------------------------
_______________________________________________
Tutor maillist - Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
|