eaponte
eaponte

Reputation: 439

list comprehension and lambda expression in python 2.6 vr. python 2.7

I am trying to back-port code written for python 2.7 into python 2.6 (the reason is that the server where the code is supposed to run has only python 2.6 and the admin refuses to install python 2.7 or higher).

In general this worked fine, but I found the following problem. In the original code the lines (or something similar):

g = lambda x : ['{:d}'.format(i) for i in x]
g([1,2,3,4])

worked fine. However, in python 2.6 they produce an error. I couldn't find anything about this topic on the documentation.

What is the reason? Is there any simple solution to this problem, i.e., a definition of the lambda expression that is equivalent (same semantics) but uses different syntax?

Upvotes: 1

Views: 3378

Answers (2)

Adam Rosenfield
Adam Rosenfield

Reputation: 400692

In Python 2.6, the field name is required (see Format String Syntax). In Python 2.7+, it can be omitted:

Changed in version 2.7: The positional argument specifiers can be omitted, so '{} {}' is equivalent to '{0} {1}'.

So if you want your code to be compatible with Python 2.6, write it like so:

g = lambda x : ['{0:d}'.format(i) for i in x]
g([1,2,3,4])

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799540

In 2.6, str.format() must have a position specifier.

g = lambda x : ['{0:d}'.format(i) for i in x]

Upvotes: 0

Related Questions