Add User Input To A List In Python

Add user input to a list in Python

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.

Code:  

# Input a sequence that will be splitted, a list of strings separated by space
myList = input().split()
 
print(myList)

Input:

1 2 3 4 5

Result:

['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.

Code:

# 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)

Input:

1 2 3 4 5 6

Result:

[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.

Code:

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)

Result:

Summary

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:

Leave a Reply

Your email address will not be published. Required fields are marked *