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

Steven D'Aprano steve at pearwood.info
Sun Dec 8 09:41:58 CET 2013


On Sun, Dec 08, 2013 at 04:10:45PM +1000, Amit Saha wrote:

> It didn't have to do with strings. It was a basic example of using
> append() which is to start with an empty list and and then build it
> incrementally:
> 
> >>> l = [ ]
> >>> l.append(1)
> # append more

If this is literally what the code does, then it's fat and slow and 
should be replaced with this:

# not this
l = []
l.append(1)
l.append(2)
l.append(x)
l.append(y)

# this is even worse, despite being shorter
l = []
for item in [1, 2, x, y]:
    l.append(item)


# this is the way to do it
l = [1, 2, x, y]


But without seeing the specific code in question, it is impossible to 
judge whether you are using append appropriately or not.



-- 
Steven


More information about the Tutor mailing list