Home > Backend Development > Python Tutorial > How to Convert User Input into a List of Integers in Python?

How to Convert User Input into a List of Integers in Python?

DDD
Release: 2024-12-16 14:55:11
Original
721 people have browsed it

How to Convert User Input into a List of Integers in Python?

Retrieve a List of Numbers from User Input in Python

In an attempt to obtain a list of numbers from user input through input() or raw_input(), a developer discovered that numbers were being treated as strings. Thus, the desired result was not achieved.

However, there is a more Pythonic approach to convert the input directly into a list of integers.

For Python 3.x, the following code accomplishes this task:

a = [int(x) for x in input().split()]
Copy after login

This code breaks down the user's input into individual strings, represented by x, using the split() method. Each string is then converted into an integer using the int() function. The resulting list of integers is stored in the variable a.

For illustration, consider the following example:

>>> a = [int(x) for x in input().split()]
3 4 5
>>> a
[3, 4, 5]
>>>
Copy after login

With this improved approach, the input is successfully transformed into a list of numbers, addressing the issue encountered in the initial attempt.

The above is the detailed content of How to Convert User Input into a List of Integers in Python?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template