General steps required to store user inputs into a list:-

  1. Declare a variable to store the values in a list.
  2. Use an iterative method to loop the user input.
  3. Append the value to the list.

We can use several methods to iterate and validate the user inputs. See the following methods to see what suits your needs:

Using range method

fruits_list = []

length = 3

for idx in range(length):
    item = input('Enter three fruit names: ')
    fruits_list.append(item)

print(fruits_list)
output 1

Here, we used the range(n)method to iterate the user inputs "n" number of times and stored it in the list using the list append() method.

Using the while loop method

fruits_list = []

length = 3

while len(fruits_list) < length:
    item = input('Enter three fruit names: ')
    fruits_list.append(item)

print(fruits_list)

This results in the same output as above.

Here, we achieved the same functionality with a while loop. The logic here differs slightly such that we are comparing the length of the list itself to the required number of inputs.

Adding validation of no duplicates

Let's introduce a small validation where the user is not allowed to add the same name to the list.

fruits_list = []

length = 3

while len(fruits_list) < length:
    item = input('Enter three fruit names: ')
    if item not in fruits_list:
        fruits_list.append(item)
    else:
        print("Duplicate name. Enter different name")

print(fruits_list)
output 2

Here we used the in operator to check whether the value already exists in the input list before appending it, or else we print a validation error message.

Notice that this validation is only possitble with the while loop method where we are actually comparing the lenght of the input list to determine when to termination the loop. Where as in the range() method, it would simply stop executing after iterating a fixed number of time.

If you found this useful, you may want to check other articles on my blog. See you in the next one.