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
Release: 2024-11-30 20:54:15
Original
211 people have browsed it

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))
Copy after login

This function will output:

[1, 2, 3]
Copy after login

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

map(int, xs)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template