-1

I have two pieces of code that do almost the same thing. Can anyone tell me what is the difference between them or which one is the proper syntax in Python?

Code 1:

p = lambda content: print(content)
p("Hello")
# Prints Hello

Code 2:

p = print
p("Hello")
# Also Prints Hello
Krishnan Shankar
  • 780
  • 9
  • 29
  • 1
    Code 1 is only useful if you specifically want to limit the parameters that can be passed to the print function. In Code 1, `p('foo', 'bar')` would fail. – tdelaney Jun 04 '20 at 00:43

2 Answers2

2

Code 1 is defining a new function, which calls the print() function. It would be more pythonic to write it as:

def p(content):
    print(content)

lambda is normally only used for anonymous functions, not named functions.

Case 2 is simply giving another name to the print function. The two names can be used interchangeably.

The lambda function only accepts one argument, while the standard print function alloes multiple positional arguments and named arguments.

So with Code 2 you can write:

p("Hello", "world", end="")

but if you try this with Code 1 you'll get an error because you gave too many arguments to the function.

If you want to define a new function that can take all the arguments that print() takes, you can use *.

def p(*args, **kwds):
    print(*args, **kwds)

or:

p = lambda *args, **kwds: print(*args, **kwds)

See What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

The first you are creating a anonymous function and assigning it to the variable p.
While in the second you are assigning the function print directly to the variable p.

Since in python functions are first class citizens, you can perform this kind of operations. Both are valid syntax, but if you only want to give a shorter name to a function, the second is simpler.

czr
  • 658
  • 3
  • 13