List mapping question

Steven Bethard steven.bethard at gmail.com
Thu Feb 3 17:29:13 EST 2005


Marc Huffnagle wrote:
> I have a number of variables that I want to modify (a bunch of strings 
> that I need to convert into ints).  Is there an easy way to do that 
> other than saying:
> 
>  > a = int(a)
>  > b = int(b)
>  > c = int(c)
> 
> I tried
> 
>  > [i = int(i) for i in [a, b, c]]
> 
> but that didn't work because it was creating a list with the values of 
> a, b and c instead of the actual variables themselves, then trying to 
> set a string equal to an integer, which it really didn't like.

Actually, that didn't work because it's a SyntaxError to have an 
assigment statement inside a list comprehension:

py> [i = int(i) for i in [a, b, c]]
Traceback (  File "<interactive input>", line 1
     [i = int(i) for i in [a, b, c]]
        ^
SyntaxError: invalid syntax

You could try something like:

py> a, b, c
('1', '2', '3')
py> a, b, c = [int(i) for i in (a, b, c)]
py> a, b, c
(1, 2, 3)

For a few variables, this is probably a reasonable solution.  For more 
than 4 or 5 though, it's going to get unreadable.  Of course for that 
many variables, you should probably be keeping them in a list instead of 
as separate names anyway...

Steve



More information about the Python-list mailing list