1

May I know why the following code does not print out [1,2,3,1,2,3]. Instead, it throws an exception. Could you show me how to make it work.

x = [1,2,3]
print apply(lambda x: x * 2, (x))

if I try the following, it works:

test1 = lambda x: x * 2
print test1(x) 
2
  • Please edit your post, include the full code that does not work, and if possible, the exception you get. Commented Feb 26, 2013 at 12:40
  • what does apply((lambda x: x * 2), (x)) do? Commented Feb 27, 2013 at 11:01

3 Answers 3

3

apply will take its second argument (which should be a tuple/list) and passes each element of this tuple as positional argument to the object you passed to apply as first argument.

That means if x = [1,2,3] and you call

apply(lambda x: x * 2, (x))

apply will call the lambda function with the arguments 1, 2, and 3, which will fail, since the lambda function only takes a single argument.


To have it work, you should but x into a tuple or a list:

print apply(lambda x: x * 2, [x])

or

# note the extra ','. (x,) is a tuple; (x) is not.
# this is probably the source of your confusion.
print apply(lambda x: x * 2, (x,)) 
Sign up to request clarification or add additional context in comments.

Comments

3

This works

x = [1,2,3]

print apply(lambda x: x * 2, [x])

However, it's probably worth noticing that apply is deprecated ever since Python 2.3

http://docs.python.org/2/library/functions.html#apply

Deprecated since version 2.3: Use function(*args, **keywords) instead of apply(function, args, keywords). (see Unpacking Argument Lists)

Comments

0

Maybe I do not understand your question, but if all you need is to "multiply" list, then simply multiply it:

xx = [1,2,3]
print(xx * 2)

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.