0

Here is my code:

map(lambda i: 3*i, map(lambda x: x, [[1, 2],[3, 4]]))

It outputs: [[1, 2, 1, 2, 1, 2], [3, 4, 3, 4, 3, 4]]

How do I modify it to print 3, 6, 9, 12?

I do not want to use append. Just map and lambda.

2 Answers 2

2

The problem you observe arises from the fact that the inner map returns a sequence of lists, not a sequence of numbers. This is because that map is iterating over a list containing smaller lists. So, if you use itertools.chain.from_iterable to flatten that list, you'll get a sequence of numbers. You can then use the outer map to triplicate them

In [67]: L = [[1, 2],[3, 4]]

In [68]: for i in map(lambda i: 3*i, itertools.chain.from_iterable(L)): print(i)
3
6
9
12
Sign up to request clarification or add additional context in comments.

Comments

1

Your code didn't work as expected because in Python the * operator is polymorphic. Thus if x and n are numbers, x*n returns the product of both numbers, but if one of the operands (say n) is an integer and the other is a sequence (.e. x is a list, a tuple or a string) the expression x*n returns the sequence which results of concatenating x with itself n times. Examples:

>>> .1 * 2.5
0.25
>>> [1, 2] * 3
[1, 2, 1, 2, 1, 2]
>>> "beep" * 2
beepbeep

In order to get the expected result you need to flatten out your list before applying map():

>>> your_list = [[1, 2], [3, 4]]
>>> flat_list = [item for sublist in your_list for item in sublist]
>>> flat_list
[1, 2, 3, 4]
>>> triples = map(lambda x: 3*x, flat_list)
>>> triples
[3, 6, 9, 12]

Actually you don't need to use map() and lambda. I think using a one-liner list comprehension would be more pythonic:

>>> triples = [3*item for sublist in your_list for item in sublist]
>>> triples
[3, 6, 9, 12]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.