Converting List of String to Integer

Gary Herron gherron at islandtraining.com
Mon Jul 21 15:20:44 EDT 2008


Samir wrote:
> Hi Everyone,
>
> I am relatively new to Python so please forgive me for what seems like
> a basic question.
>
> Assume that I have a list, a, composed of nested lists with string
> representations of integers, such that
>
> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
>
> I would like to convert this to a similar list, b, where the values
> are represented by integers, such as
>
> b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]
>
> I have unsuccessfully tried the following code:
>
> n = []
> for k in a:
>     n.append([int(v) for v in k])
> print n
>
> Does anyone know what I am doing wrong?
>
> Thanks in advance.
>
> Samir
> --
> http://mail.python.org/mailman/listinfo/python-list
>   

You didn't tell us how it failed for you, so I can't guess what's wrong.

However, your code works for me:

 >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
 >>> n = []
 >>> for k in a:
...    n.append([int(v) for v in k])
...
 >>> print n
[[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]

(Although you seem to have confused variables b and n.)

Gary Herron





More information about the Python-list mailing list