Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return list of items in list greater than some value

Tags:

python

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?

like image 455
Carlton Avatar asked Jan 03 '11 20:01

Carlton


People also ask

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 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 return a list in Python?

To return a list in Python, use the return keyword and write the list you want to return inside the function. Python list is like the array of elements created using the square brackets. Lists are different from arrays as they can contain elements of various types.


1 Answers

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() 
like image 56
Michael Mrozek Avatar answered Sep 21 '22 01:09

Michael Mrozek