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) 
Michał Niklas
  • 53,067
  • 18
  • 70
  • 114
Test Test
  • 31
  • 4

3 Answers3

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,)) 
sloth
  • 99,095
  • 21
  • 171
  • 219
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)

Xuan
  • 5,255
  • 1
  • 34
  • 30
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)
Michał Niklas
  • 53,067
  • 18
  • 70
  • 114