Moving list entries from one list to another

Alex Martelli aleax at aleax.it
Sat Jul 13 09:54:29 EDT 2002


Emile van Sebille wrote:
        ...
>>>> l1 = [1,4,7,10,32,45]
>>>> l2 = [4,32]
>>>>
>>>> def f(lst): return 1
> ...
>>>> [ l1.append(x) for x in l2 if f(x) ]
> [None, None]
>>>> l1.sort()
>>>> l1
> [1, 4, 4, 7, 10, 32, 32, 45]
>>>>
> 
> There, only took a minute.  Is that fast enough?  ;-)

We can do a bit better by not abusing list comprehensions:

l1.extend([ x for x in l2 if f(x) ])
l1.sort()

and to make this a move, as requested, rather than a copy,
a third statement:

l2[:] = [ x for x in l2 if not f(x) ]


Using list comprehensions for loops not meant to build lists
is not quite kosher.  It may work, but it IS allocating a
list of results without real purpose.  You may be able to
use a list comprehension with extend, like here; or, code a
bona fide loop -- that's still a possibility, remember:-).


List's sort method is *incredibly* fast if the list is
already sorted except for a few items out of place at the
end.  This approach may be able to exploit this superb
speed if only a few items are being appended to l1.  If
many items are being appended, then O(N log N) is the best
we can do anyway.  Thus, this approach is near-optimal.



Alex




More information about the Python-list mailing list