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?
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.
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 .
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With