0

Here's the prompt for the problem:

Write code using zip and filter so that all provided lists are combined into one big list and assigned to the variable 'larger_than_3' if they are both longer than 3 characters each.

l1 = ['left', 'up', 'front']

l2 = ['right', 'down', 'back']

I am able to solve this by the following line of the code:

larger_than_3 = list(filter(lambda x: len(x[0]) > 3 and len(x[1]) > 3, list(zip(l1, l2))))

I understand that here python interpreter treats x as a tuple and uses[] to access each of the elements in original lists, respectively. Because lambda takes in only one parameter as input, I also created the following code:

l_lst = list(zip(l1, l2))       
larger_than_3 = list(filter(lambda (a,b): len(a)>3 and len(b)>3, l_lst))

But python says this line of code is invalid syntax. I can't quite figure out why it is wrong as the lambda function could take in a tuple as its parameter.

2
  • In the last bit of code, you added parentheses around the lambda parameters. The first lambda correctly has no parentheses around its parameter list. Commented Jun 27, 2022 at 20:38
  • Python used to allow that (putting a parenthesized sublist of parameters in parenthesis, to unpack a single provided parameter), but that was causing some sort of problem (debugger support, I think), so was removed. Commented Jun 27, 2022 at 20:39

1 Answer 1

1

It's a syntax error, the lambda function can take multiple variables

lambda a,b: print(a,b)

but in this case it's not actually necessary because of the way the data is being passed to the lambda by filter, re-writing it to:

larger_than_3 = list(filter(lambda a: len(a[0])>3 and len(a[1])>3, l_lst))

makes it function the same way as the first part! because a is set to each item in the list, thing for a in l_list so a = ('left','right') so we can index it and get the expected output!

Sign up to request clarification or add additional context in comments.

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.