"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Efficiently Get a List of Integers as Input from a User in Python?

How Can I Efficiently Get a List of Integers as Input from a User in Python?

Published on 2024-12-23
Browse:513

How Can I Efficiently Get a List of Integers as Input from a User in Python?

Get a List of Numbers as Input from the User: Pythonic Solution

When attempting to retrieve a list of numbers from a user using input() or raw_input(), you may encounter unexpected results due to Python's tendency to interpret input as strings. To avoid this issue and obtain a list of integers, employ a more Pythonic approach using list comprehension and input splitting.

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

Example:

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

This concise solution utilizes:

  • Splitting input: Split the user's input string into a list of substrings using the split() method. By default, it splits at whitespace characters.
  • Casting to integers: Employ list comprehension to convert each substring into an integer, ensuring that the resulting list contains numeric values.

By utilizing this approach, you can effortlessly capture a list of numbers from the user in Python, eliminating the need for complex regular expressions or additional parsing steps.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3