If you are looking for an instruction to add user input to a list in Python, keep reading our article. Today, we will show you how to input a list of data. Let’s start now.
How to add user input to a list in Python
Use input() combine with split()
The fastest way to input a list is using the split() function after calling the input() function. This combination enables the user to input a sequence string to get a list of inputs separated by space. The disadvantage is that the result is also a list of strings.
# Input a sequence that will be splitted, a list of strings separated by space myList = input().split() print(myList)
1 2 3 4 5
['1', '2', '3', '4', '5']
Use the map function
The most common and effective way to input a list is by using the function map. We suggest that you should use this method to input when participating in contests or practicing algorithms in Codeforce, LeetCode, and HackerRank.
This way, we will create a list using the list() function. For each element of the list, we will use the map() function with int and input() to create integers and map each of them to each element. We will also use strip() and split() functions to modify the input sequence. Please take a look at our example code below.
# Input a sequence number that will be splitted and map to each element of the list myList = list(map(int, input().strip().split())) print(myList)
1 2 3 4 5 6
[1, 2, 3, 4, 5, 6]
Append the list after each input
Another way to input a list is step-by-step input elements and append them one by one to the list. In this approach, the input is discrete, but in the end, after appending them all to the list, your result is a continuous sequence. Every input is separated by pressing enter.
- Step 1: Determine the number of the input.
- Step 2: Create a loop to enter each element.
- Step 3: Enter the element at each loop and append it to the list.
print("Enter number of elements: ") n = int(input()) myList =  # Loop n times to input each element for i in range(n): print("Enter the element", i+1) # Input an element i = input() # Append it to the list myList.append(i) print(myList)
Our tutorial provides detailed examples of how to add user input to a list in Python. We hope that you will like this article. If you have any troubles, do not hesitate to give us your questions. We will answer as possible. Thanks for reading!
Maybe you are interested:
- Join a list with a newline character in Python
- Add two lists element-wise in Python
- Remove an element from a list by index in python
My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.
Name of the university: HUST
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP