Python get all elements greater than

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

>>> 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 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!!

Let’s start by noting that the key assumption we will be making throughout this article is that the aim is to get the elements as values, not to count them – but return a list with the corresponding values. Lists are one of the most common data structures used in Python and are created using square brackets []. They are defined as being ordered, changeable (or mutable), and allow duplicate values. The values that make up a list are called its elements, or its items

To begin, we can create a list. As we are going to be working on finding elements greater than a certain value we will make a list with numbers only – both integers (whole numbers) and floats (decimal places):

list1 = [22, 34, 44, 88, 2, 1, 7.5, 105, 333, 7]

  • Method 1: List Comprehension
  • Method 2: The Filter Function
    • Filter with lambda
    • Filter without lambda
  • Method 3: Using NumPy
  • Conclusion

Method 1: List Comprehension

Arguably the most straightforward way of filtering our list is with list comprehension. This will involve simple code to iterate over each element and compare against a given value. For example, assuming we only want a list containing elements, or items, with a value greater than 7, our syntax would be:

list2 = [item for item in list1 if item > 7]
print(list2)
# [22, 34, 44, 88, 7.5, 105, 333]

In the above example, we have asked Python to iterate over each item in list1 and return a new list (list2) of all items greater than 7.

We can also sort the new list if necessary:

list2.sort()
print(list2)
# [7.5, 22, 34, 44, 88, 105, 333]

Method 2: The Filter Function

As an alternative to list comprehension, we can use the built-in filter() function.

Filter with lambda

Just as a reminder, a lambda function is defined as a small anonymous function (i.e., it has no name) that can take any number of arguments but can only have one expression.

list3 = filter(lambda x: x > 7, list1)

In the code, we are using our filter function to extract values (x) from our list1 if x is greater than 7. So now if we call our list3 we get:

print(list3)
# 

Probably not what you were expecting! This is because in Python version 3 and above the filter function returns an object, and the syntax above represents the object ID in memory not the values.  As we want the actual values from the list, we have to call the object as a list itself:

print(list(list3))
# [22, 34, 44, 88, 7.5, 105, 333]

Whilst we have the output we want, a key thing to note is that the filter function does not hold any values in memory. Therefore, if we call the list again it will return empty:

print(list(list3))
# []

So,  if we need to call the list again – as a sorted list, for example, we need to run our lambda function once more:

list3 = filter(lambda x: x > 7, list1)
print(list(sorted(list3)))
# [7.5, 22, 34, 44, 88, 105, 333]

Filter without lambda

As an alternative to lambda, we can also use filter with one of Python’s special functions which replaces our comparison operator i.e., less than <, greater than > etc. These special functions are defined by double underscores ( __ ) — that’s why they are called dunder methods.

If we want to create a list of all items greater than 7, we will need to get our function to filter or remove any items less than 7, as follows:

list4 = filter((7).__lt__, list1)
print(list4)
# 

In the above code the __lt__ syntax is the equivalent to < or less than, so we are creating an object called list4 that filters out any number less than 7 from list1. As with lambda as we are using filter, we get an object returned so we need to call the values as a list:

print(list(list4))
# [22, 34, 44, 88, 7.5, 105, 333]

As this method still uses the filter function the values are not held in memory, so if we call the list again it will return empty:

print(list(list4))
# []

To get the list again, this time sorted, we would need to run the function once more but this time we can just request the values sorted:

list4 = filter((7).__lt__, list1)
sorted(list4)
# [7.5, 22, 34, 44, 88, 105, 333]

Method 3: Using NumPy

A final option would be to use the NumPy module to achieve our goal, but depending on the nature of our initial list, this might be slight overkill.

This process is slightly more complex as we need to import the NumPy module and then convert our list into an array as follows:

import numpy as np
list1 = [22, 34, 44, 88, 2, 1, 7.5, 105, 333, 7]
list1 = np.array(list1)
print(list1)
# array([ 22. , 34. , 44. , 88. , 2. , 1. , 7.5, 105. , 333. , 7. ])

One thing to note is that the integer values have automatically been converted to floats when the array is created. Once we have list1 as a NumPy array we can run some simple code to iterate over our array and return all the values in the array greater than 7. We can also sort the return array directly using np.sort:  

list2 = np.sort(list1[list1 > 7])
print(list2)
# array([  7.5,  22. ,  34. ,  44. ,  88. , 105. , 333. ])

Now that we have the correct, sorted values, the last step is to convert them back to a list using the tolist() method:

list3 = list3.tolist()
# [7.5, 22.0, 34.0, 44.0, 88.0, 105.0, 333.0]

Conclusion

In this article we have looked at the various ways of getting elements in a list above a certain value, and once again Python has shown us there are several ways of achieving this.

Personally, I find the list comprehension method the most useful as it is simple and does exactly what is required. However, we have used a basic, small data set in our examples so I can appreciate that if you are using large amounts of data using NumPy may be more appropriate as the module is designed to handle more complex data.

Whilst the filter function does provide the same result, the fact that it returns an object rather than the list values, means we have to rerun the function each time we want the values. Depending on the application this could be impractical.

How do you find greater than value in Python?

Well, to write greater than or equal to in Python, you need to use the >= comparison operator. It will return a Boolean value – either True or False. The "greater than or equal to" operator is known as a comparison operator. These operators compare numbers or strings and return a value of either True or False .

How do you check if all elements in a list are greater than 0?

Using all() function we can check if all values are greater than any given value in a single line. It returns true if the given condition inside the all() function is true for all values, else it returns false.

How do you find the number greater than a value in a list Python?

Method 5 : Using bisect() + sort() The combination of sort() and bisect() , can actually perform the task of binary search, and hence getting the index and subtracting the size of list can actually help us get elements that are greater than particular element in the list.

How do you compare values in a list Python?

Using list. sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.