Borislav Hadzhiev
Tue Jun 21 2022·2 min read
Photo by Mike Kotsch
To add user input to a list in Python:
range
to iterate N times.append
the value to the list.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']
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.
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.
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
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
.
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 original string into a list of substrings using a delimiter.
The method takes the following 2 parameters:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At most maxsplit splits are done (optional) |
If the separator is not found in the string, a list containing only 1 element is returned.