In this tutorial, we will learn how to print a user input list in Python. **Python** is a high-level, interpreted, and general-purpose programming language that is used to build applications ranging from web development, data analysis, artificial intelligence, and more.
Python allows you to receive input from the user which helps to make the programs interactive. This tutorial will teach you how to take multiple inputs from the user, store them in a list, and print that list.
Step 1: Initialize an empty list
First things first, we will create an empty list to store the user input values. To create an empty list, we simply assign a pair of square brackets []
to a variable, like so:
1 |
user_input_list = [] |
Step 2: Receive input from the user
Now, we will use a loop to receive multiple inputs from the user. For this tutorial, we will use the for
loop. The basic syntax of a for loop in Python is as follows:
1 2 |
for variable in range(start, stop, step): # code to execute |
We will use the input()
function to receive inputs from the user. The input()
function reads a line from the input, converts it into a string, and returns it. To allow the user to input an integer, we will wrap the input()
function inside the int()
function.
1 2 3 4 5 |
number_of_inputs = int(input("Enter the number of elements you want to add to the list: ")) for i in range(number_of_inputs): user_input = int(input("Enter a number: ")) user_input_list.append(user_input) |
Here, we first ask the user to input the number of elements they want to add to the list. Then, we create a for loop that iterates for the given number of times and receives the input from the user using the input()
function for each iteration. We then append the user input to our previously initialized list using the append()
function.
Step 3: Print the list
Once you have received all the user inputs and stored them in the list, you can simply print the list using the print()
function.
1 |
print("Your list is: ", user_input_list) |
Full Code:
1 2 3 4 5 6 7 8 9 |
user_input_list = [] number_of_inputs = int(input("Enter the number of elements you want to add to the list: ")) for i in range(number_of_inputs): user_input = int(input("Enter a number: ")) user_input_list.append(user_input) print("Your list is: ", user_input_list) |
Output:
Enter the number of elements you want to add to the list: 5 Enter a number: 10 Enter a number: 20 Enter a number: 30 Enter a number: 40 Enter a number: 50 Your list is: [10, 20, 30, 40, 50]
In this example, the user inputs the number of elements as 5 and adds 5 integer elements to the list. The output displays the final list with all the user input elements.
Conclusion
By following this tutorial, you have learned how to create a list that stores multiple user input values in Python. You have also learned how to use loops and basic input-output functions in Python to create an interactive program that takes input from users and displays the result.