[Tutor] list comprehensions

Jeff Shannon jeff@ccvcorp.com
Wed, 21 Aug 2002 10:01:06 -0700


Gregor Lingl wrote:

>  >>> [word for word in tl if len(word) == max(map(len,tl))]
> ['eeeee']

Note, however, that this is *much* less efficient than the original for-loop code,
because it recalculates the maximum length for *each* element of the list.  Since
finding the max length examines each element of the list, this takes time
proportionate to the square of the list length, while the original version is
linear.  This won't make a noticeable difference for small lists, but will
certainly be significant if the list is an entire dictionary file.  You can regain
linear time for list comprehensions by breaking this into two steps (as Prahlad
did).

Jeff Shannon
Technician/Programmer
Credit International