[Tutor] operator * of the list and tuple

Kyle Brooks anotequaltob at gmail.com
Thu Aug 2 14:53:39 CEST 2007


Hi.

The explanation on that page may be a bit confusing, so I will add to it.

If you think of L * n as something similiar to doing a shallow copy of
the list L n times, then it makes some sense:

>>> a = []
>>> L = [[]]
>>> for i in xrange(5):
     ...  a.append(L[:][0])

has the same (or similiar) effect as

>>> a = [[]]*5

Both have the side effect noted in the text: that

>>> a[0].append(42)

modifies a single list, as you can see if you ask for a unique identifier:

>>> [id(e) for e in L]
[number repeated 5 times]

The alternative way:

>>> L = [[] for i in xrange(5)]

works because the code "[]", which creates a new empty list, is
executed 5 times, and creates 5 different lists.

On 8/2/07, Kent Johnson <kent37 at tds.net> wrote:
> Yang wrote:
> > So, can somebody tell me how the * operator of list and tuple work,
> > and how can we make use of it?
>
> A bit more here:
> http://docs.python.org/lib/typesseq.html
>
> See especially note (2)
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list