how to find items matching in string length from 2 lists in python using functional programming

Question:

I have 2 lists of strings and I want to compare and return the strings that have the same length in the same position in each of the string lists. I understand how to do this with loops and comprehensions so I’ve been trying to do this using zip, lambdas, and filter which I want to practice more but have been running into a wall after endless searching/googling.

list1 = ["aaa", "bb", "c", "wwwww"]
list2 = ["dddd", "xx", "a", "abcd"]

Should return: [("bb", "xx"), ("c", "a")]

Heres what I’ve been using but doesnt seem to be working:

list(filter(lambda param: len(param) == len(param), zip(list1, list2)))
Asked By: D-Money

||

Answers:

Using filter:

list1 = ["aaa", "bb", "c", "wwwww"]
list2 = ["dddd", "xx", "a", "abcd"]

output = list(filter(lambda z: len(z[0]) == len(z[1]), zip(list1, list2)))
print(output) # [('bb', 'xx'), ('c', 'a')]

Using list comprehension, which I prefer due to readability:

output = [(x, y) for x, y in zip(list1, list2) if len(x) == len(y)]
Answered By: j1-lee

param in lambda is a tuple when using zip. Try using it like this:

list1 = ["aaa", "bb", "c", "wwwww"]
list2 = ["dddd", "xx", "a", "abcd"]
list(filter(lambda param: len(param[0])==len(param[1]), zip(list1,list2)))
[('bb', 'xx'), ('c', 'a')]
Answered By: Rabinzel