Convert a tuple of strings to a tuple of integers in Python

avatar

Borislav Hadzhiev

Last updated: Jul 2, 2022

banner

Photo from Unsplash

Convert a tuple of strings to a tuple of integers in Python #

To convert a tuple of strings to a tuple of integers:

  1. Use a generator expression to iterate over the tuple.
  2. Convert each tuple item to an integer by passing them to the int() class.
  3. Use the tuple() class to convert the generator object to a tuple.
main.py
tuple_of_strings = ('10', '20', '30', '40') tuple_of_integers = tuple(int(item) for item in tuple_of_strings) # 👇️ (10, 20, 30, 40) print(tuple_of_integers)

We used a generator expression to iterate over the tuple of strings.

Generator expressions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we pass the tuple element to the int() class to convert it to an integer.

The int class returns an integer object constructed from the provided number or string argument.

Alternatively, you can use the map() function.

To convert a tuple of strings to a tuple of integers:

  1. Pass the int() class to the map() function.
  2. The map() function will pass each item of the tuple to the int() class.
  3. The new tuple will only contain integer values.
main.py
tuple_of_strings = ('10', '20', '30', '40') tuple_of_integers = tuple(map(int, tuple_of_strings)) # 👇️ (10, 20, 30, 40) print(tuple_of_integers)

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

This approach is a bit more implicit than using a generator expression.

The map() function returns a map object, so we had to use the tuple() class to convert the map object to a tuple.

Tuples are very similar to lists, but implement fewer built-in methods and are immutable (cannot be changed).

Since tuples cannot be changed, the only way to convert a tuple of strings to a tuple of integers is to create a new tuple that contains integer values.

Which approach you pick is a matter of personal preference. I'd go with the generator expression as I find it more direct and more explicit.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.