How to take a List from user input in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
7 min

banner

# Table of Contents

  1. Add user input to a list in Python
  2. Take a list of integers from user Input in Python
  3. Take list user input using str.split()
  4. Take a list of integers from user Input using str.split()
  5. Take list user input using a while loop
  6. Take a list of integers from user Input using a while loop
  7. Take a list of lists user input
  8. Take a two-dimensional list of integers from user input

# Add user input to a list in Python

To add user input to a list in Python:

  1. Declare a variable that stores an empty list.
  2. Use the range() class to loop N times in a for loop.
  3. On each iteration, append the input value to the list.
main.py
shopping_list = [] list_length = 3 for idx in range(list_length): item = input('Enter item to buy: ') shopping_list.append(item) print(shopping_list) # ๐Ÿ‘‰๏ธ ['apple', 'banana', 'kiwi']

add user input to list

The code for this article is available on GitHub

The code sample prompts the user for input 3 times and adds each value to the list.

The list.append() method adds an item to the end of the list.

The example uses the range() class, but you can also use a while loop if you want to make sure the list has a length of at least N items.

main.py
shopping_list = [] max_length = 3 while len(shopping_list) < max_length: item = input('Enter item to buy: ') shopping_list.append(item) print(shopping_list) # ๐Ÿ‘‰๏ธ ['apple', 'banana', 'kiwi']

If the list has a length of less than 3, we keep prompting the user for input.

This approach is especially useful when you want to make sure there aren't any duplicates in the list.
main.py
shopping_list = [] max_length = 3 while len(shopping_list) < max_length: item = input('Enter item to buy: ') # ๐Ÿ‘‡๏ธ Make sure item is not in the list before appending if item not in shopping_list: shopping_list.append(item) print(shopping_list) # ๐Ÿ‘‰๏ธ ['apple', 'banana', 'kiwi']
The code for this article is available on GitHub

We used an if statement to check if the value the user entered isn't in the list before appending it.

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise it evaluates to False.

x not in l returns the negation of x in l.

An alternative approach is to ask the user to enter multiple, space or comma-separated words and split the string on the separator.
main.py
user_input = '' while user_input.count(' ') < 2: user_input = input('Enter at least 3 space-separated shopping items: ') shopping_list = user_input.split(' ') print(shopping_list) # ๐Ÿ‘‰๏ธ ['apple', 'banana', 'kiwi']

Note that this approach is a bit harder to validate.

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

If the separator is not found in the string, a list containing only 1 element is returned.

Here is another example of taking a list from user input.

main.py
my_list = [] for _ in range(3): my_list.append(input('Enter a country: ')) print(my_list)

list user input for loop

The code for this article is available on GitHub

The code snippet loops 3 times, takes input from the user and appends it to a list.

The list.append() method adds an item to the end of the list.

I used an underscore for the variable name because we don't need to access it.

# Take a list of integers from user Input in Python

If you need to store integer values in a list, use the int() class to convert the input strings to integers.

main.py
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)

list user input for loop numers

The code for this article is available on GitHub

The input() function takes an optional prompt argument and writes it to standard output without a trailing newline.

The function then reads the line from the input, converts it to a string and returns the result.

The input() function is guaranteed to return a string, even if the user enters an integer.

We used a try/except statement to handle the ValueError that is raised if the int() class is called with a value that is not a valid integer.

An alternative approach is to ask the user to enter multiple, space or comma-separated words and split the string on the separator.

# Take list user input using str.split()

This is a three-step process:

  1. Use the input() function to take input from the user.
  2. Use the str.split() method to split the string on each whitespace.
  3. The split() method will return a list containing the words the user entered.
main.py
user_input = input('Enter space-separated shopping items: ') shopping_list = user_input.split() print(shopping_list) # ๐Ÿ‘‰๏ธ ['apple', 'banana', 'kiwi']

python list user input split

The code for this article is available on GitHub

The str.split() method splits the string into a list of substrings using a delimiter.

When no separator is passed to the str.split() method, it splits the input string on one or more whitespace characters.

# Take a list of integers from user Input using str.split()

If you need to convert the values to numbers, use a list comprehension.

main.py
user_input = input('Enter space-separated integers: ').split() list_of_integers = [int(item) for item in user_input] print(list_of_integers) # ๐Ÿ‘‰๏ธ [1, 2, 3]

list user input split integers

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we pass the current list item to the int() class to convert it to an integer.

# Take list user input using a while loop

This is a three-step process:

  1. Declare a new variable and initialize it to an empty list.
  2. Use a while loop to iterate as long as a condition is met.
  3. On each iteration, append the input value to the list.
main.py
my_list = [] user_input = '' while len(my_list) < 3: user_input = input('Enter a word: ') my_list.append(user_input) print(my_list)
The code for this article is available on GitHub

The example uses a while loop to ask the user for input until the list contains at least 3 items.

# Take a list of integers from user Input using a while loop

You can also use this approach to make sure the list contains at least N integers.

main.py
my_list = [] user_input = '' 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)

list user input at least n values

The code for this article is available on GitHub

The example uses a while loop to iterate until the list contains at least 3 integers taken from user input.

The continue statement is used to continue to the next iteration of the loop.

If the code in the try block raises a ValueError, the except block runs, where we use the continue statement to continue to the next iteration.

When validating user input in a while loop, we use the continue statement when the input is invalid, e.g. in an except block or an if statement.

Alternatively, you can use a while True loop with a break statement.

main.py
my_list = [] user_input = '' 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 equal to or greater than 3.

If the condition is met, we use the break statement to exit out of the loop.

The break statement breaks out of the innermost enclosing for or while loop.

# Take a List of Lists user input

To take a list of lists user input:

  1. Use a for loop to iterate N times.
  2. Use the input() function to take multiple inputs from the user.
  3. Add the input values to a list and append the list to the original list.
main.py
list_of_lists = [] user_input = '' 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)

user input list of lists

The code for this article is available on GitHub

We used a for loop to iterate 2 times.

On each iteration, we take user input 2 times, place the values in a list and append the list to another list.

# Take a two-dimensional list of integers from user input

To take a two-dimensional list of integers from user input:

  1. Use a for loop to iterate N times.
  2. Use the input() function to take multiple inputs from the user.
  3. Use the int() class to convert the values to integers.
  4. Add the input values to a list and append the list to the original list.
main.py
list_of_lists = [] user_input = '' 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)

two dimensional list of integers user input

The code for this article is available on GitHub

We used a for loop to iterate 2 times.

On each iteration, we take user input 2 times and convert the values to integers.

Lastly, we place the values in a list and append the list to another list.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev