0

I have a list like

myList = [1,2,3,4,5,6]

I want to check:

lambda x : True if (x > 0 and x < 7) else False

I want to apply the above lambda function for each element of a list, and in a long if statement, is it possible?

if len(myList) < 10 and (lambda parameter_list: expression):

I understood that we can use lambda when we need to by pass functions which do not actually require an input even we define it.

Ruli
  • 2,592
  • 12
  • 30
  • 40

3 Answers3

0

Your answer is here:

myList=[1,10,1,20]
[True if i>0 and i< 7 else False for i in myList]

prints:

[True, False, True, False]

List comprehensions has syntax sugar for (lambda x:...)(n), therefore here True if i>0 and i< 7 else False is a shortcut for

[(lambda x:True if x>0 and x< 7 else False)(i) for i in myList]
fukanchik
  • 2,811
  • 24
  • 29
0

There is no need for a lambda expression here; you can use the all function and a generator expression:

if len(myList) < 10 and all(0 < x < 7 for x in myList):

A lambda expression is just a way of defining a function. Not all functions can be defined using a lambda expression, just those that could be written as a single return statement:

x = lambda ...: ...

is the same as

def x(...):
    return ...

The benefit is that you don't need to come up with a name that would only be used one time.

chepner
  • 497,756
  • 71
  • 530
  • 681
-1

It was great thanks really. One more and last question:

if you want to control user inputs which are expected as comma separated like 1,2,3,4

how would you check this? I was originally planning to check the numbers between 0 and 7 for the dice game that's why I asked the question.

I have a few thoughts already which one do you think is better analytic approach?

1. If there is an input, you always expect odd number of input length because:

    1,2,3 --  len(input) = 5
    1  -- len(input) = 1
    1,2,3,4,5 len(input) = 9  
     


2. Or length of used commas in the input will be also half of the total input -1:

    1,2,3,4,5 len(input) = 9
    
    len(re.findall(',', keep_input)) = (9-1)/2

I also check, before these two conditions, if the user input makes sense, if it is pure number and commas, if anything else provided etc. I don't accept and request once more input from user that is it.

Note: after finishing the game I will share it with you guys to give idea to everyone. At the moment I'm trying to normalise user input, filter it and reject etc. The main part of code (success cases working pretty well).

Kind Regards