Cast a List from One Type to Another in Python

One of the key properties of Python is that it is a weakly typed language. In contract to strongly typed languages such as Java, you don’t have to define the class of an object when you instantiate it. This offers much flexibility. But sometimes you want to be able to define precisely what class of objects you are working with. So let’s say you have a list of String objects, and you want to convert all of them to numbers so you can do some kind of mathematical operation on them.

x = ['123','456','789','111']
sum(x) # this would cause an error because you can't use sum on Strings

But it’s easy in python to convert that list from Strings to Integers.

y = [int(z) for z in x]
sum(y) # 1479

This example may not arise too often in the “real world,” but it illustrates the easy with which you can work with lists. The first line creates a variable y which is a list where the int function is applied to each item in x. Please note that if any of the String objects contained a value that could not be converted to an integer, you would get an error. So you might need to create a custom function that could handle that logic. Then you code might look something like this:

y = [someFunction(z) for z in x]
sum(y) # 1479

Leave a Reply