Last active
July 17, 2025 15:18
-
-
Save sloanlance/c38f8dfcde2c71fec7e6e769fcfbbd36 to your computer and use it in GitHub Desktop.
Python: map equivalent of nested for loops
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def nestedFor(m, n): | |
"""add each element of m to each element of n""" | |
result = [] | |
for i in m: | |
for j in n: | |
result.append(i+j) | |
return result | |
def mapEquiv(m, n): | |
"""add each element of m to each element of n""" | |
return sum(map(lambda c: list(map(c, n)), | |
map(lambda a: lambda b: a + b, m)), []) | |
m = [10, 20, 30] | |
n = [3, 4, 5] | |
print(nestedFor(m, n)) # [13, 14, 15, 23, 24, 25, 33, 34, 35] | |
print(mapEquiv(m, n)) # [13, 14, 15, 23, 24, 25, 33, 34, 35] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment