0

how can I rewrite the following code by using lambda function?the problem i have is to make x as variable so I can return different list based on input

s_list = [1,2,3,4,5,6]
def f(x):
    return [a for a in s_list if a not in x]

print(f([1,2]))#[3,4,5,6]
print(f([4,6]))#[1,2,3,5]
3
  • 2
    Just curious why you ask this? Commented Apr 2, 2018 at 18:34
  • need to return a complicated list that filter some flied value Commented Apr 2, 2018 at 18:38
  • 1
    Which most likely means you don't want a lambda... how about you help saying what you really want to do? Commented Apr 2, 2018 at 18:40

3 Answers 3

2

If you don't need s_list like a argument, you can use this:

F = lambda x: [a for a in [1,2,3] if a not in x]

and if you need s_list like an argument, you could make this:

F = lambda x, s_list: [a for a in s_list if a not in x]
Sign up to request clarification or add additional context in comments.

2 Comments

what if I would x to have default value as empty list, so if not x provide it, return all s_list?
@jacobcan118 As I describe in stackoverflow.com/a/49607920/7738328 it is possible to have default arguments also in lambda functions. Thus, you can do lambda x=[]: ... if you want a default argument. Note that default arguments need to be last in list, so either you have to have s_list as the first argument or just use s_listfrom the global (outer) scope.
1

Here's a way to write your function using filter:

def f2(x):
    return filter(lambda a: a not in x, s_list)

print(f2(x=[1,2]))
#[3, 4, 5, 6]
print(f2(x=[4,6]))
#[1, 2, 3, 5]
print(f2(x=[]))
#[1, 2, 3, 4, 5, 6]

Or if you wanted it to be a function of both s_list and x:

def f3(s_list, x):
    return filter(lambda a: a not in x, s_list)

print(f3(s_list, x=[1,2]))
#[3, 4, 5, 6]
print(f3(s_list, x=[4,6]))
#[1, 2, 3, 5]
print(f3(s_list, x=[]))
#[1, 2, 3, 4, 5, 6]

Comments

0

You can achieve that by using Filter method :

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

x_=[1,2]

print(list(filter(lambda x:x not in x_,s_list)))

output:

[3, 4, 5, 6]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.