Add user input to a list in Python

avatar

Borislav Hadzhiev

Last updated: Jun 21, 2022

banner

Photo from Unsplash

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 a range to iterate N times.
  3. On each iteration, prompt the user for input.
  4. append the 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 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 list before appending if item not in shopping_list: shopping_list.append(item) print(shopping_list) # 👉️ ['apple', 'banana', 'kiwi']

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.

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.