[Tutor] Prepend to a list? (fwd)

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Mar 20 04:18:54 CET 2005

---------- Forwarded message ----------
Date: Sun, 20 Mar 2005 00:05:07 -0500
From: Jay Loden <python at jayloden.com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] Prepend to a list?

Thanks for the replies everyone,

I ended up changing my approach so that it won't require appending to the
list, but it's good to know anyway because I'm sure it will come up in the
future.  I'm sort of surprised there isn't a prepend() method for lists, but
I'm sure there's a reason.

Danny, thanks for the extra info, I'll definitely keep that in mind.  The
script(s) I'm working on are for a content management system using Python/PHP
in combination. Most of the data is small sets, but fairly frequently run, so
I'm looking for more efficient code in terms of CPU cycles on the server. In
such a case, is one of the approaches better, or are they fairly equal?


On Saturday 19 March 2005 06:08 pm, you wrote:
> Hi Jay,
> Liam and Sean pointed out that you can either do a combination of
> reverse() and append(), or you can use insert().
> How often are you planning to prepend onto your lists, though?  The
> performance of both approaches can be quite different, depending on input
> size.  Do you plan to do a lot of prepends at a time?  Also, are you
> dealing with short lists?
> If you're dealing with short lists, either solution will work fine.  But
> if your lists grow to something much larger (say, in the tens of
> thousands), then you might need a more specialized solution, such as a
> 'deque':
>     http://www.python.org/doc/lib/module-collections.html
> A dequeue behaves like a list, but it also supports very fast "prepend"
> (in the dequeue documentation, the 'appendleft()' method), so if your
> needs are specialized, a deque might be an appropriate data structure for
> you.
> Best of wishes!

More information about the Tutor mailing list