1

Having following list

base_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

If I want to separate it into 2 lists by criteria x > 5 in one line I will do sonething like this

 list_1 = [num for num in base_list if num < 5]
 list2 = [num for num in base_list if num > 5]

I'm wondering if it possible to make it one line?

Something like this

list1, list2 = [num for num in base_list if num < 5 and_here_else_part_for_second_list]
micgeronimo
  • 2,069
  • 5
  • 23
  • 44
  • `list_1 = [num for num in base_list if num < 5]; list2 = [num for num in base_list if num > 5]` -- Good enough for "one line"? :) – Dolda2000 Jan 27 '15 at 20:57

1 Answers1

0

Sure it's possible to fit it in one line (and even one statement)...

list_1, list2 = [num for num in base_list if num < 5], [num for num in base_list if num > 5]

But you probably don't want to do that :-) (there aren't any advantages that I can see)...

There are other ways that you could fit it into 1 comprehension, but none of them are particularly "clean". What you have is about as good as it gets I'm afraid.

mgilson
  • 300,191
  • 65
  • 633
  • 696