List comprehensions' ugliness (Was: Re: How to explain exactly what "def" does?)

Ian Bicking ianb at colorstudy.com
Thu Feb 6 05:30:28 EST 2003


On Thu, 2003-02-06 at 03:46, Donnal Walter wrote:

> > mylist.extend(otherlist) is better.
> > 
> 
> mylist = mylist + otherlist
> 
> The above assignment statement is an idiom that I have (perhaps naively) 
> adopted. Is the .extend syntax more efficient? I can also see where it 
> might be considered more readable or more accurate. (?)

Yes, extend is more efficient -- it extends the list in place.  So, for
example:

>>> mylist = [1, 2]
>>> list2 = mylist
>>> mylist = mylist + [3, 4]
>>> mylist
[1, 2, 3, 4]
>>> list2
[1, 2]
>>> mylist = list2
>>> mylist.extend([3, 4])
>>> mylist
[1, 2, 3, 4]
>>> list2
[1, 2, 3, 4]


Note also that 
  mylist += otherlist
is equivalent to mylist.extend(otherlist)

-- 
Ian Bicking  ianb at colorstudy.com  http://colorstudy.com
4869 N. Talman Ave., Chicago, IL 60625  /  773-275-7241
"There is no flag large enough to cover the shame of 
 killing innocent people" -- Howard Zinn





More information about the Python-list mailing list