Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Casting part of a 2D list to int in Python

I have to convert all string elements of a 2-D list to integers except for the first element. For example, for a list:

result = [['foo', '2', '21', '48'], ['bar', '18', '180', '54']]

I only wish to change the type of the "numbers" in the list to int type (say, ‘2’, ’21’, ’48’ in first row).

I have tried using a list comprehension,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

result = [int(x) for x in result[i]]
# where i is the traversal variable

but this gives
invalid literal for int() with base 10: 'foo'
which is precisely what I am trying to avoid.

Any ideas on how to achieve this without creating another copy of the list? I want to reflect the changes back to the original list.

>Solution :

Perhaps you’re looking for str.isdigit:

out = [[int(x) if x.isdigit() else x for x in lst] for lst in result]

Output:

[['foo', 2, 21, 48], ['bar', 18, 180, 54]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading