[Tutor] Nested list anomaly
dman
dman@dman.ddts.net
Mon, 29 Apr 2002 20:04:04 -0500
--pWyiEgJYm5f9v55/
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable
On Tue, Apr 30, 2002 at 10:07:32AM +1000, Hugh Stewart wrote:
| Test 1:
| >>> c1 =3D [[0]*2]*3
| >>> c1
| [[0, 0], [0, 0], [0, 0]]
This looks good, but what you have is a 3-element list where all
elements are identical references to the same 2-element list. Since
lists are mutable, if you change the list, the change is seen by all
the references to it.
| Test 2:
| >>> c2 =3D [[0,0]]*3
Same situation.
| Test 3:
| >>> c3 =3D [[0,0],[0,0],[0,0]]
Here's what you wanted -- a 3-element list where each element is a
_separate_ list.
A shorter way of writing that (for longer lists) is :
c =3D []
for i in range(3) :
c.append( [0]*2 )
or
c =3D [ [0]*2 for i in range(3) ]
-D
--=20
Come to me, all you who are weary and burdened, and I will give you
rest. Take my yoke upon you and learn from me, for I am gentle and
humble in heart, and you will find rest for your souls. For my yoke
is easy and my burden is light.
Matthew 11:28-30
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg
--pWyiEgJYm5f9v55/
Content-Type: application/pgp-signature
Content-Disposition: inline
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org
iEYEARECAAYFAjzN7YQACgkQO8l8XBKTpRTPSQCdF7CH9x50rkSx9ogq2NCWuS4N
FAkAnjReNp6MWLNO7TWmdza7QPdKhd6d
=73Cg
-----END PGP SIGNATURE-----
--pWyiEgJYm5f9v55/--