Home > Blockchain >  How do I get the output to only be numbers within a list that are greater than x?
How do I get the output to only be numbers within a list that are greater than x?

Time:06-20

def list_number(mylist,x):
    y=[i if i>x else False for i in mylist]
    return y

I am trying to get only the numbers that are greater than x in a list to be my output and I also need it to return False if there are no numbers greater than x.

For example mylist=[1,2,3,4,5,6,7,8,9] and x=5, I want my output to be [6,7,8,9]. if x=10, I want my output to be false.

I cannot use any methods like .append or .sort

CodePudding user response:

The mistake in your example is your incorrect usage of list comprehension. Here are simple examples to show you how to use list comprehension with conditional statements:

iterator = range(10)
# Example (list comprehension with if statement)
[x for x in iterator if x > 5]
# [6, 7, 8, 9]

# Example (list comprehension with if...else statement)
[x if x > 5 else 0 for x in iterator]
# [0, 0, 0, 0, 0, 0, 6, 7, 8, 9]

As for your specific question, you can use the information above to create a function like this:

def list_number(mylist, x):
    y = [n for n in mylist if n > x]
    if not y:
      return False
    return y

CodePudding user response:

You can use a list comprehension and then return False if the list is empty. Using the or operator allow it to simplify it as it will execute the second statement if the first one is considered as False, so if the list is empty.

def list_number(mylist, x):
    return [y for y in mylist if y > x] or False

Another way it can be done is using a filter:

def list_number(mylist, x):
     return list(filter(x.__lt__, mylist)) or False

x.__lt__ correspond to the less than operator on the value of x.


Either way,

>>> list_number(list(range(10)), 5)
[6, 7, 8, 9]

>>> list_number(list(range(10)), 11)
False

CodePudding user response:

I'd say this code is pretty easy to read and predictable. No need to have any advanced knowledge. (except typehints)

from typing import List, Union

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = 10


def greater_than(list_uf_nums: List[int], num: int) -> Union[List[int], bool]:
    return_list = [y for y in list_uf_nums if y > num]
    if not return_list:
        return False
    return return_list


print(greater_than(l, x))

CodePudding user response:

You can use the fact that empty list is a false value in python.
This way your code will always return a list, which is much better than returning a List | boolean

from typing import List

def list_number(my_list: List[int], x: int) -> List[int]:
    return [num for num in my_list if num > x]

result: List[int] = list_number([4,6,89,21],7)
if(result):
  print('non empty result')
else:
  print('empty result')
  
result: List[int] = list_number([4,6,89,21],790)
if(result):
  print('non empty result')
else:
  print('empty result') 

output

non empty result
empty result
  • Related