π‘ Problem Formulation: In various scenarios, a Python program needs to prompt the user to enter multiple values at once, which will be stored as a list. For example, the user could be prompted to input a list of numbers to be averaged, or a catalogue of items to be processed later. The desired output is a list containing the items the user entered, suitable for further manipulation within the program.
Method 1: Using input() with split()
This method captures a line of input, typically a string of values, and then uses the split() function to convert it into a list. By default, split() will divide the input string on whitespace, so itβs perfect for inputs such as space-separated values.
β₯οΈ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month
Here’s an example:
user_input = input("Enter a list of numbers separated by space: ")
number_list = [int(x) for x in user_input.split()]
print(number_list)The output may look like this if a user types 1 2 3 4:
[1, 2, 3, 4]
This snippet first takes a string of numbers separated by spaces. It then splits the string into a list of strings and converts each to an integer, resulting in a list of numbers.
Method 2: Using map() with input()
Similar to Method 1, Method 2 offers a streamlined approach to converting the input directly to a desired data type using the map() function, which applies a function to every item of the input.
Here’s an example:
number_list = list(map(int, input("Enter a list of numbers separated by space: ").split()))
print(number_list)The output for the user input 5 10 15 would be:
[5, 10, 15]
This code takes space-separated input values and splits them into a list, just like Method 1. However, it uses map() directly within the list constructor to perform the conversion process even more succinctly.
Method 3: Reading Multiple Lines of Input
When the user needs to input a list item per line, this method will collect each line until an empty line or a specific termination input is reached.
Here’s an example:
prompt = "Enter items for the list one per line, press enter on an empty line to finish.\n"
lines = []
while True:
line = input(prompt)
if line:
lines.append(line)
else:
break
print(lines)A user adding apple, banana and cherry with blank line to finish would produce:
['apple', 'banana', 'cherry']
In this snippet, each iteration of the loop captures a single line of input and appends it to a list unless the line is empty, which breaks the loop.
Method 4: Reading a List Literal
For more advanced users who are comfortable with Python syntax, this method involves directly inputting a list literal which is evaluated using ast.literal_eval().
Here’s an example:
import ast
list_str = input("Enter the list using Python's list syntax: ")
number_list = ast.literal_eval(list_str)
print(number_list)If a user enters the valid Python list [25, 50, 100], the output will be:
[25, 50, 100]
This code prompts for a string representing a Python list and then safely evaluates the string to be an actual list object using ast.literal_eval().
Bonus One-Liner Method 5: Comprehension with input().split()
For a Pythonic one-liner approach, you can use a list comprehension combined with input().split() to create a neat single line of code.
Here’s an example:
number_list = [int(x) for x in input("Enter numbers: ").split()]Assuming a user input of 7 14 21, the output will be:
[7, 14, 21]
This one-liner uses a list comprehension to split the input into a list of strings and then converts each list item into an integer.
Summary/Discussion
- Method 1: Using
input()withsplit(). Strengths: Straightforward for users to understand. Weaknesses: Assumes knowledge of correct delimiters and doesn’t handle type conversions in complex cases. - Method 2: Using
map()withinput(). Strengths: Concise and efficient, especially for directly converting to a specific data type. Weaknesses: Less readable for newcomers to Python. - Method 3: Reading Multiple Lines of Input. Strengths: Natural for user input that is inherently line-oriented. Weaknesses: Requires an extra loop and a way to signal the end of input.
- Method 4: Reading a List Literal. Strengths: Allows for complex list inputs and is powerful in the hands of experienced users. Weaknesses: Prone to errors if the user is unfamiliar with list syntax.
- Method 5: Comprehension with
input().split(). Strengths: Pythonic and compact. Weaknesses: Mixes input and processing in a single line, which can be a debugging challenge.
