defining the behavior of zip(it, it)

Alex Martelli aleax at mail.comcast.net
Thu Nov 24 18:21:59 EST 2005


<rurpy at yahoo.com> wrote:
   ...
> > >>> d=deque([1,2,3])
> > >>> d[:]
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in ?
> > TypeError: sequence index must be integer
> > >>> deque(d)
> > deque([1, 2, 3])
> > >>>
> >
> > I.e., NOT all sequences implement the unreadable x[:] form.
> >
> > The way that DOES work with all sequences is typeyouwant(sequence).
> 
> I'm sorry, I don't understand.  Does deque return a sequence?

There is no universally accepted definition of what "is a sequence" in
Python, but the deque type meets most criteria.

> The doc says it returns a deque object, and without further info
> I would not expect [:] to work.  Is it a sequence because it has
> the same methods as a sequence?

Workable definitions are usually operational ones, yes.


> Whatever, I gather my old book is outdated and the blessed
> way now to (shallow) copy a sequence is (as you say)
> "typeyouwant(sequence)" which I will make a note of.
> 
> Thanks for updating me.

You're welcome, but be aware that this is MY thesis and not all accept
it.  somesequencetype(someiterable) is a general way to make a new
instance of type 'somesequencetype' and accepts a wide variety of types
for arguments, namely all iterables.  list(somelist) is slightly less
compact than somelist[:] when you know you start with a list instance
and want a shallow copy thereof, but I see no good reason to specialcase
this occurrence AND use an unreadable idiom in it, when the nice,
general, readable idiom is perfectly serviceable.


Alex



More information about the Python-list mailing list