Reputation: 3
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.
Upvotes: 0
Views: 49
Reputation: 74
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!
Upvotes: 1