94

I have the following list

j=[4,5,6,7,1,3,7,5]

What's the simplest way to return [5,5,6,7,7] being the elements in j greater or equal to 5?

Carlton
  • 943
  • 1
  • 6
  • 4
  • 3
    and what will be the fastest? – Oren Dec 02 '15 at 16:47
  • for sure you should not sort them before filtering it. Since that will slow down a lot. Instead start filtering it, and then sort out the result if you need that sorted – Pietro Speroni Mar 20 '18 at 16:36
  • 1
    NOTE for duplicate closers: for questions asking about *what the syntax means* for a list comprehension, consider https://stackoverflow.com/questions/6475314. – Karl Knechtel Jun 30 '22 at 22:19

7 Answers7

130

You can use a list comprehension to filter it:

j2 = [i for i in j if i >= 5]

If you actually want it sorted like your example was, you can use sorted:

j2 = sorted(i for i in j if i >= 5)

Or call sort on the final list:

j2 = [i for i in j if i >= 5]
j2.sort()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
  • There's no need to use a list comprehension when you're going to feed it to `sorted` anyway. Hopefully you do know generator expressions and just forget how well they apply in that case ;) –  Jan 03 '11 at 20:18
  • 1
    @Michael that would be a nice addition though! :) – ismail Jan 03 '11 at 20:20
  • @delnan Oh, yes; I just copy/pasted the first line and wrapped it in `sorted()`. Fixed, thanks – Michael Mrozek Jan 03 '11 at 20:21
  • @İsmail - `numpy` has a `where` function (http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html). But in `numpy` you could also do `j2 = j[j >= 5]` if `j` is an ND array. – mtrw Jan 03 '11 at 20:28
18

A list comprehension is a simple approach:

j2 = [x for x in j if x >= 5]

Alternately, you can use filter for the exact same result:

j2 = filter(lambda x: x >= 5, j)

Note that the original list j is unmodified.

Justin Ardini
  • 9,768
  • 2
  • 39
  • 46
13

You can use a list comprehension:

[x for x in j if x >= 5]
sepp2k
  • 363,768
  • 54
  • 674
  • 675
4

Use filter (short version without doing a function with lambda, using __le__):

j2 = filter((5).__le__, j)

Example (Python 3):

>>> j=[4,5,6,7,1,3,7,5]
>>> j2 = filter((5).__le__, j)
>>> j2
<filter object at 0x000000955D16DC18>
>>> list(j2)
[5, 6, 7, 7, 5]
>>>

Example (Python 2):

>>> j=[4,5,6,7,1,3,7,5]
>>> j2 = filter((5).__le__, j)
>>> j2
[5, 6, 7, 7, 5]
>>>

Use __le__. I recommend this. It's very easy. __le__ is your friend.

If want to sort it to the desired output (both versions):

>>> j=[4,5,6,7,1,3,7,5]
>>> j2 = filter((5).__le__, j)
>>> sorted(j2)
[5, 5, 6, 7, 7]
>>>

Use sorted

Timings:

>>> from timeit import timeit
>>> timeit(lambda: [i for i in j if i >= 5]) # Michael Mrozek
1.4558496298222325
>>> timeit(lambda: filter(lambda x: x >= 5, j)) # Justin Ardini
0.693048732089828
>>> timeit(lambda: filter((5).__le__, j)) # Mine
0.714461565831428
>>>

So Justin wins!!

With number=1:

>>> from timeit import timeit
>>> timeit(lambda: [i for i in j if i >= 5],number=1) # Michael Mrozek
1.642193421957927e-05
>>> timeit(lambda: filter(lambda x: x >= 5, j),number=1) # Justin Ardini
3.421236300482633e-06
>>> timeit(lambda: filter((5).__le__, j),number=1) # Mine
1.8474676011237534e-05
>>>

So Michael wins!!

>>> from timeit import timeit
>>> timeit(lambda: [i for i in j if i >= 5],number=10) # Michael Mrozek
4.721306089550126e-05
>>> timeit(lambda: filter(lambda x: x >= 5, j),number=10) # Justin Ardini
1.0947956184281793e-05
>>> timeit(lambda: filter((5).__le__, j),number=10) # Mine
1.5053439710754901e-05
>>>

So Justin wins again!!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
3

In case you are considering using the NumPy module, it makes this task very simple, as requested:

import numpy as np

j = np.array([4, 5, 6, 7, 1, 3, 7, 5])

j2 = np.sort(j[j >= 5])

The code inside of the brackets, j >= 5, produces a list of True or False values, which then serve as indices to select the desired values in j. Finally, we sort with the sort function built into NumPy.

Tested result (a NumPy array):

array([5, 5, 6, 7, 7])
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

Since your desired output is sorted, you also need to sort it:

>>> j=[4, 5, 6, 7, 1, 3, 7, 5]
>>> sorted(x for x in j if x >= 5)
[5, 5, 6, 7, 7]
Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
0

There is another way,

j3 = j2 > 4
print(j2[j3])

It was tested in Python 3.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Harsha VK
  • 11
  • 1
  • Do it really works? I got `TypeError: '>' not supported between instances of 'list' and 'int'` – Mikhail_Sam Dec 16 '19 at 08:15
  • Is this a response to previous answers? `j2` is a processed version of `j` in them. Can you [make](https://stackoverflow.com/posts/53434704/edit) the code self-contained? But ****** ***without*** ****** "Edit:", "Update:", or similar - the answer should appear as if it was written today. – Peter Mortensen Dec 16 '22 at 20:19