Home >Backend Development >Python Tutorial >How to Convert a Python List of Strings to a List of Integers?

How to Convert a Python List of Strings to a List of Integers?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 20:54:15381browse

How to Convert a Python List of Strings to a List of Integers?

Converting Strings to Integers in a Python List

How can you transform a list of strings that represent integers, such as ['1', '2', '3'], into a corresponding list of integers, such as [1, 2, 3]?

To accomplish this conversion, Python offers a straightforward solution:

Given the list xs = ['1', '2', '3']:

Utilize the map function to apply the int function to each element of xs, creating a new list where each string is replaced by its integer value. The resulting object from map is an iterable; you can call the list function on this iterable to transform it into a formal list.

list(map(int, xs))

This function will output:

[1, 2, 3]

In Python 2, the list function wasn't necessary because map returned a list directly:

map(int, xs)

The above is the detailed content of How to Convert a Python List of Strings to a List of Integers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn