3 ms·
The preferred syntax, which is more flexible and doesn't leak the loop variable, is to use generator expressions: >>> x = ['1', '2', '3', '4', '5'] >>> y =
by dlitz 14y ago
The preferred syntax, which is more flexible and doesn't leak the loop variable, is to use generator expressions:
>>> x = ['1', '2', '3', '4', '5']
>>> y = list(int(i) for i in x)
>>> y
[1, 2, 3, 4, 5]
It also works for tuples:
>>> y = tuple(int(i) for i in x)
>>> y
(1, 2, 3, 4, 5)
And for dicts:
>>> y = dict((i, int(i)) for i in x)
>>> y
{'1': 1, '3': 3, '2': 2, '5': 5, '4': 4}
And if you want a lazily-evaluated generator:
>>> y = (int(i) for i in x)
>>> y
<generator object <genexpr> at 0xb7655eb4>
Also, as I mentioned before, generator expressions don't leak the loop variable:
>>> i = 42
>>> y = list(int(i) for i in x)
>>> i
42
>>> y = [int(i) for i in x]
>>> i
'5'
See http://www.python.org/dev/peps/pep-0289/ http://www.python.org/dev/peps/pep-0289/