How can I generate a new List which is filtered and sorted in a Single Line command using List Comprehension in Python?

Viewed 41
a=[5,11,10,65,100,1,15,19,20,25,32,35,41]

I want to get multiples of 5 sorted using List Comprehension. I know how to apply List comprehension but not know how to apply filter and sort. List Comprehension:-

b=[a for i in a]
1 Answers

List comprehensions can be used in Python (language reference here) to implement mapping or filtering:

  • mapping [<expr> for <it> in <iterable>]
  • filtering [<expr> for <it> in <iterable> if <cond>]

Note that <expr> can be a conditional expression (or ternary operator) : <expr1> if <cond> else <expr2>.

There is no support for sorting upon generation, but for sorting you can use one of the following:

  • sorted() which creates a new sorted list from its iterable input
  • list.sort() method which sorts the list in-place.

Notice that for sorted() you may wish to avoid the list comprehension (to avoid using extra temporary space at the cost of a slight reduction in speed) and just use its generator expression: sorted(<expr> for <it> in <iterable> if <cond>) (without the square brackets).

For more information on sorting in Python, see the official Sorting HOW TO.


With the variables from your question this would be:

# : with `list.sort()`
b_sort = [x for x in a if x % 5 == 0]
print(b_sort)
# [5, 10, 65, 100, 15, 20, 25, 35]
b_sort.sort()
print(b_sort)
# [5, 10, 15, 20, 25, 35, 65, 100]

# : with `sorted()`
b_sorted = sorted(x for x in a if x % 5 == 0)  # with generator expr
print(b_sorted)
# [5, 10, 15, 20, 25, 35, 65, 100]

Note that you cannot use list.sort() with a one-liner because it acts in-place and returns None:

# `b_sort` contains `None` and the list is lost
b_sort = [x for x in a if x % 5 == 0].sort()
print(b_sort)
# None  
Related