ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-list
python-list
Re: Moving list entries from one list to another
by Alex Martelli other posts by this author
Jul 13 2002 1:54PM messages near this date
Re: Moving list entries from one list to another | Re: Moving list entries from one list to another
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

-- 
http://mail.python.org/mailman/listinfo/python-list
Thread:
JB
JB
Bengt Richter
JB
Alex Martelli
Bengt Richter
JB
JB
JB
JB
JB
JB
Bengt Richter
Alex Martelli
Alex Martelli
Alex Martelli
Emile van Sebille
=?iso-8859-1?q?Fran=E7ois?= Pinard

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved