[Tutor] Aschenputtel problem

Orri Ganel singingxduck at gmail.com
Sat Sep 17 05:47:09 CEST 2005


Christopher Arndt wrote:

>Hi,
>
>I wonder if there is a shorter form of the following idiom:
>
>list1 = []
>list2 = []
>for item in original_list:
>    if condition(item):
>        list1.append(item)
>    else:
>        list2.append(item)
>
>(optional step:)
>
>original_list[:] = list1
>
>
>I call this the "Aschenputtel" problem, because it is described by the famous
>quote from the fairy tale as told by the Grimm brothers:
>
>"Die guten ins Töpfchen, die schlechten ins Kröpfchen."
>
>(The good ones in the pot, the bad ones in the crop)
>
>Chris
>
>
>  
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>
Well, you there is a way to do it in one line, by having a list of list 
comprehensions:

 >>> olist = range(10)
 >>> list1, list2 = [[x for x in olist if not x % 2], [i for i in olist 
if i % 2]]
 >>>
 >>> list1
[0, 2, 4, 6, 8]
 >>> list2
[1, 3, 5, 7, 9]

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.



More information about the Tutor mailing list