-2

Using zip and list comprehension, create a new list, L3, that sums the two numbers if the number from L1 is greater than 10 and the number from L2 is less than 5. This can be accomplished in one line of code.

I have tried the codes below. Can anyone explain why python complains?

L1 = [1, 5, 2, 16, 32, 3, 54, 8, 100]
L2 = [1, 3, 10, 2, 42, 2, 3, 4, 3]
L3 = map(lambda  (x1,x2): x1 + x2  if(x1 > 10 and x2 < 5)  , zip(L1,L2))
L4 = map(lambda  x: x[0] + x[1]  if(x[0] > 10 and x[1] < 5)  , zip(L1,L2))
print(L3)
print(L4)
wjandrea
  • 28,235
  • 9
  • 60
  • 81

2 Answers2

2

This is an XY problem. You're using a map when it asks for a list comprehension. It's essentially asking for a filter, not a map.

>>> [x1+x2 for x1, x2 in zip(L1, L2) if x1>10 and x2<5]
[18, 57, 103]

You could do it in a functional style, but it's so ugly. Don't do this.

L3 = list(map(
    lambda t: t[0]+t[1],
    filter(
        lambda t: t[0]>10 and t[1]<5,
        zip(L1, L2)
        )
    ))
print(L3)  # -> [18, 57, 103]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

Have a look here: The lambda function must have a return value and if your if statement is not true, there is none. Therefore, you would have to add an else statement, for example:

L4 = map(lambda  x: x[0] + x[1]  if (x[0] > 10 and x[1] < 5) else 0, zip(L1,L2))

Results in

[0, 0, 0, 18, 0, 0, 57, 0, 103]

Your first try (L3) does not work because lambda can no longer unpack tuples in python 3.x (see: here)

Please also note that map() returns an object and in order to print its content you would have to call

print(list(map_object))
# in your case:
print(list(L4))
# or set()

Edit based on comment: if you really want a one-liner and as your first sentence says "using zip and list comprehension" and you want to leave out 0s, then this might work and is easier than map and lambda:

L3 = [x[0]+x[1] for x in zip(L1,L2) if (x[0] > 10 and x[1] < 5)]

Edit 2 if you really, really, really insist on using map and lambda:

L4 = map(lambda  x: x[0] + x[1], filter(lambda x: (x[0] > 10 and x[1] < 5), zip(L1,L2)))
BenB
  • 658
  • 2
  • 10
  • I had tried with the code you have written above too, the problem is that there are 0s in between and it takes another line of code to get rid of them. The question is asking for one line of code.. –  Nov 21 '20 at 20:08
  • I edited my answer: L3 = [x[0]+x[1] for x in zip(L1,L2) if (x[0] > 10 and x[1] < 5)] might be what you are looking for. – BenB Nov 21 '20 at 20:19
  • I was hoping to write it with map. maybe it's not possible in one line code then. Thanks! –  Nov 21 '20 at 20:26
  • Ok, here is one more try using the filter method which has a similar syntax to map: L4 = map(lambda x: x[0] + x[1], filter(lambda x: (x[0] > 10 and x[1] < 5), zip(L1,L2))) – BenB Nov 21 '20 at 20:35