0

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)))
j1-lee
  • 13,764
  • 3
  • 14
  • 26
D-Money
  • 137
  • 1
  • 12
  • Hint: when it iterates over the results from `zip(list1, list2)`, what do you think each list will look like? Therefore, what values do you expect `param` to have in the `lambda`? Did you try to check that? Related: how could `len(param) == len(param)` ever be false? What do you actually want to be on each side of the `==`? – Karl Knechtel Sep 27 '22 at 04:31
  • "I understand how to do this with loops and comprehensions" - it would help to start by making sure you have working code with that approach, and then compare and contrast. I can't think of any *sensible* approaches, whether via a `for` loop, comprehension, `list`/`filter` or anything else, that *don't* use `zip`. So either way you would have to be familiar with what `zip` does. – Karl Knechtel Sep 27 '22 at 04:33
  • If the confusion is about how to write `lambda`s in general - they are **just** syntactic sugar for functions that don't have a name, contain a single expression, and `return` the result of that expression. – Karl Knechtel Sep 27 '22 at 04:34

2 Answers2

0

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)]
j1-lee
  • 13,764
  • 3
  • 14
  • 26
0

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')]
Rabinzel
  • 7,757
  • 3
  • 10
  • 30