NEWBIE: for statement in "dive into python" gives syntax err
Sean 'Shaleh' Perry
shalehperry at attbi.com
Tue Jul 23 15:56:07 EDT 2002
On 23-Jul-2002 Mack wrote:
> Hi
>
> I need some pointers. I've been reading the "Dive into python" tutorial
> and tried some statements on my machine. Redhat 7.1 with python 1.5.2
>
>>>> li = [1, 9, 8, 4]
>>>> li
> [1, 9, 8, 4]
>>>> [elem*2 for elem in li]
> File "<stdin>", line 1
> [elem*2 for elem in li]
> ^
> is what i'm getting. Is my python too old? Is something else wrong?
> I've just cut and pasted from the tutorial into python ide.
>
yep. "Dive Into Python" has a lot of code which only works under 2.1.x and up.
The syntax you pasted is called a 'list comprehension' and was added in the
2.x series.
The 1.5 idiom for the above would have been:
output = map(lambda elem: elem * 2, li)
or
def double(item):
return item * 2
output = map(double, li)
or even
output = []
for elem in li:
output.append(elem * 2)
More information about the Python-list
mailing list