How to Collect List Input from Users in Python
Collecting input from users and storing it in a list is a fundamental task in interactive applications.
This guide explores various methods for taking list input from users, including techniques for handling strings, numbers, multiple inputs on one line, validating the input and working with multi-dimensional lists.
Adding User Input to a List with a Loop
The most common way to add user input to a list is by using a for
loop and the append()
method.
shopping_list = []
list_length = 3
for idx in range(list_length):
item = input('Enter item to buy: ')
shopping_list.append(item)
print(shopping_list) # Output: (list of items)
- The
for
loop executeslist_length
times, each time asking user for input and appending that input to a list.
Looping Until a Specific Length
Use a while
loop when you want to continue collecting input until the list reaches a certain length:
shopping_list = []
max_length = 3
while len(shopping_list) < max_length:
item = input('Enter item to buy: ')
shopping_list.append(item)
print(shopping_list) # Output: (list of items)
- The
while
loop keeps running until the length of the list is at leastmax_length
.
Handling Duplicates
To prevent duplicate items in your list, check the input for membership before appending it.
shopping_list = []
max_length = 3
while len(shopping_list) < max_length:
item = input('Enter item to buy: ')
if item not in shopping_list:
shopping_list.append(item)
print(shopping_list) # Output: (list of unique items)
- The
if item not in shopping_list
condition ensures that no duplicates will be added to the list.
Taking Multiple Space/Comma-Separated Inputs on One Line
To prompt the user to enter multiple values separated by whitespace (spaces or tabs) or commas, you can use the split()
method.
Splitting the Input String
Here’s an example of how you would use split()
with the default separator to split on whitespace characters:
user_input = input('Enter at least 3 space-separated shopping items: ')
shopping_list = user_input.split()
print(shopping_list) # Output: (list of words)
- If no delimiter is provided to
split()
, it will split the string at any amount of whitespace.
Taking a List of Integers
You may also want to collect a list of integers from the user.
Handling Invalid Integer Input
To convert the user's input to integers while handling potential ValueError
exceptions, use try
/except
:
my_list = []
for _ in range(3):
try:
my_list.append(int(input('Enter a number: ')))
except ValueError:
print('The provided value is not an integer.')
print(my_list)
- This approach prompts the user to enter integer values and provides feedback if non-integer values are used.
With str.split()
If you expect the user to enter space-separated integers, you can split the input and use a list comprehension to convert values to integers:
user_input = input('Enter space-separated integers: ').split()
list_of_integers = [int(item) for item in user_input]
print(list_of_integers) # Output: (list of integers)
- The
split()
method creates a list of substrings, and the list comprehension converts them to integers.
Taking List Input Using a while
Loop
A while
loop is a good fit for continuous input collection or for conditional collection.
Looping Until N Integers are Entered
To collect a list of N integers, use a while loop that keeps asking for input until a certain condition is met:
my_list = []
while len(my_list) < 3:
try:
user_input = int(input('Enter an integer: '))
my_list.append(user_input)
except ValueError:
print('Enter a valid integer')
continue
print(my_list) # Output: (list of integers)
- This code continues to prompt for input until the list has 3 integers.
- The
continue
keyword skips the rest of the code in the while loop and restarts the loop from the beginning.
Alternatively, a while True
loop with a break
statement can also be used:
my_list = []
while True:
if len(my_list) >= 3:
break
try:
user_input = int(input('Enter an integer: '))
my_list.append(user_input)
except ValueError:
print('Enter a valid integer')
continue
print(my_list)
- The if statement checks if the length of the list is at least 3, in which case we exit the loop with
break
.
Taking a List of Lists as Input
To collect multiple lists of values, use nested loops. For example, here is how you can prompt for two inputs on every iteration and append the result to an outer list:
list_of_lists = []
for _ in range(2):
user_input_1 = input('Enter a word: ')
user_input_2 = input('Enter another word: ')
list_of_lists.append([user_input_1, user_input_2])
print(list_of_lists)
Output:
[['word1', 'word2'], ['word3', 'word4']]
- The outer
for
loop is responsible for iterating N times. - On each iteration, two
input()
calls prompt for user input, and the two strings are stored as a list, which then is appended to thelist_of_lists
list.
You can also collect lists of integers, by converting the string input from input()
to integers using int()
.
list_of_lists = []
for _ in range(2):
user_input_1 = int(input('Enter an integer: '))
user_input_2 = int(input('Enter another integer: '))
list_of_lists.append([user_input_1, user_input_2])
print(list_of_lists)
Output:
[[int1, int2], [int3, int4]]