1

I have some code to test other codes that I've written(in ipython notebook).

print_closest = lambda w, wl: print('{}: {} ({})'.format(w, *closest_match(w, wl)))

This is the code I have and it works on python 3 environment. However, it doesn't work on python 2.7. Instead, it throws an error below.

print_closest = lambda w, wl: print('{}: {} ({})'.format(w, *closest_match(w, wl)))
                                      ^
SyntaxError: invalid syntax

I'd like to make a change on the code above in order to get it work on python2.7 environment as well as python3.

Can anyone please tell me how? Thanks in advance.

jsh114
  • 43
  • 1
  • 4
  • 1
    See: http://stackoverflow.com/questions/2970858/why-doesnt-print-work-in-a-lambda Basically it's not supported under python 2.7 – Aviad Oct 25 '16 at 17:03
  • Thanks a lot for all the answers replied. I didn't know it was duplicate question. – jsh114 Oct 25 '16 at 17:12

2 Answers2

1

In Python 2, print is a statement, not a function, and cannot be used in a lambda expression. You can make it work by adding the print_function feature:

from __future__ import print_function
print_closest = lambda w, wl: print('{}: {} ({})'.format(w, *closest_match(w, wl)))
Zulu
  • 8,765
  • 9
  • 49
  • 56
larsks
  • 277,717
  • 41
  • 399
  • 399
1

In Python 2, print is a statement, not a function (as a function, using it would be an expression). lambdas can consist only of expressions, not full statements.

That said, you can get the Py3 print function on Py2. In modules where you want to switch, add the following as the very first line of code in the file (after any shebang or encoding comments, before everything else):

from __future__ import print_function

That will make print a function as it is in Py3.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271