Python Get a list as input from user


In this article we will see you how to ask the user to enter elements of a list and finally create the list with those entered values.

With format and input

The format function can be used to fill in the values in the place holders and the input function will capture the value entered by the user. Finally, we will append the elements into the list one by one.

Example

listA = []
# Input number of elemetns
n = int(input("Enter number of elements in the list : "))
# iterating till the range
for i in range(0, n):
   print("Enter element No-{}: ".format(i+1))
   elm = int(input())
   listA.append(elm) # adding the element
print("The entered list is: \n",listA)

Output

Running the above code gives us the following result −

Enter number of elements in the list : 4
Enter element No-1:
7
Enter element No-2:
45
Enter element No-3:
1
Enter element No-4:
74
The entered list is:
[7, 45, 1, 74]

With map

Another approach is to ask the user to enter the values continuously but separated by comma. Here we use the map function together the inputs into a list.

Example

listA = []
# Input number of elemetns
n = int(input("Enter number of elements in the list : "))
# Enter elements separated by comma
listA = list(map(int,input("Enter the numbers : ").strip().split(',')))[:n]
print("The entered list is: \n",listA)

Output

Running the above code gives us the following result −

Enter number of elements in the list : 4
Enter the numbers : 12,45,65,32
The entered list is:
[12, 45, 65, 32]

Entering list of lists

We can also use input function twice so that we can create a list of lists. Use the range function to keep account on number of elements to be entered and the format function to enter the elements one by one. Finally, we append each entered element to the newly created list.

Example

listA = []
# Input number of elemetns
n = int(input("Enter number of elements in the list : "))
# Each sublist has two elements
for i in range(0, n):
   print("Enter element No-{}: ".format(i + 1))
   ele = [input(), int(input())]
   listA.append(ele)
print("The entered list is: \n",listA)

Output

Running the above code gives us the following result −

Enter number of elements in the list : 2
Enter element No-1:
'Mon'
3
Enter element No-2:
'Tue'
4
The entered list is:
[["'Mon'", 3], ["'Tue'", 4]]

Updated on: 09-Jul-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements