Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

list(filter(lambda param: len(param) == len(param), zip(list1, list2)))

>Solution :

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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading