[Tutor] Alternatives to append() for "growing" a list

Amit Saha amitsaha.in at gmail.com
Sun Dec 1 09:53:11 CET 2013


On Sun, Dec 1, 2013 at 5:04 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sun, Dec 01, 2013 at 02:32:38PM +1000, Amit Saha wrote:
>> Hello,
>>
>> I was told by someone (as a comment) that a code snippet such as this
>> "would make Pythonistas talk my ear off about how evil the append()"
>> function is:
>
> There is absolutely nothing wrong with append. Either you have
> misunderstood, or the person who told you this was smoking crack.

heh, no I literally quote the person above, so I think I understood
him alright.

>
>> >>> mylist = []
>> >>> mylist.append(1)
>> # a number of times over
>
> However, growing a list one item at a time using append like this is too
> much hard work. Some better solutions:
>
> # You have an existing list, and want to append a bunch of things to it
> mylist.extend([x, y+1, z*2])
>
> # You want a list consisting of the same objects repeated many times
> mylist = [0, 1, 2]*100  # like [0, 1, 2, 0, 1, 2, 0, 1, 2, ...]
>
> # You want to create a list containing known objects
> mylist = [1, 2, 4, 8, 16, 32, 64]
>
> # Like above, but using a list comprehension
> mylist = [2**n for n in range(7)]
>
> # You don't know how many things you want to add.
> mylist = []
> x = 1
> while x < 100:
>     mylist.append(x)
>     x = 3*x-1
>
> and so on. As you can see, append has its job to do.
>


The last case is the closest to the context in which I used the above
code construct.


>
>> I have some ideas that on an append() the list's internal size
>> increases (doubled?) since CPython over-allocates memory, and such.
>
> Not just on append. Any operation that adds or deletes items from a list
> might trigger a re-size. If the list needs to increase, it will double
> in size up to some maximum, then it will grow by a smaller amount. The
> purpose of this is that *on average* appending to the list will take a
> fixed amount of time.
>
>
>> So, the question is: what is the alternative to growing a list when I
>> have no idea what items or how many may be there?
>
> Don't worry about growing the list. That's all handled for you as part
> of the list interface. The whole point of using Python is to not have to
> worry about internal details like that.


Right, that's what I thought. Good that I checked here, now I can
write a nice reply to the comment :-)

Thanks Steven and Dave.

Best,
Amit.


-- 
http://echorand.me


More information about the Tutor mailing list