Open In App
Related Articles

Get a list as input from user in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

We often encounter a situation when we need to take a number/string as input from the user. In this article, we will see how to get input a list from the user using Python

Example: 

Input : n = 4,  ele = 1 2 3 4
Output : [1, 2, 3, 4]

Input : n = 6, ele = 3 4 1 7 9 6
Output : [3, 4, 1, 7, 9, 6]

Get a list as input from user in Python using Loop

Python3

# creating an empty list
lst = []
 
# number of elements as input
n = int(input("Enter number of elements : "))
 
# iterating till the range
for i in range(0, n):
    ele = int(input())
    # adding the element
    lst.append(ele) 
 
print(lst)

                    

Output: 

Python | Get a list as input from user

 

Time Complexity: O(n), where n is the length of the list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list 

Get a list as input from user in Python With exception handling  

Python3

# try block to handle the exception
try:
    my_list = []
 
    while True:
        my_list.append(int(input()))
 
# if the input is not-integer, just print the list
except:
    print(my_list)

                    

Output: 

Python | Get a list as input from user

 

Get a list as input from user in Python Using map() 

Python3

# number of elements
n = int(input("Enter number of elements : "))
 
# Below line read inputs from user using map() function
a = list(map(int,
    input("\nEnter the numbers : ").strip().split()))[:n]
 
print("\nList is - ", a)

                    

Output: 

Python | Get a list as input from user

 

Get a list as input from user in Python List of lists as input 

Python3

lst = []
n = int(input("Enter number of elements : "))
 
for i in range(0, n):
    ele = [input(), int(input())]
    lst.append(ele)
 
print(lst)

                    

Output: 

Python | Get a list as input from user

 

Get a list as input from user in Python Using List Comprehension and Typecasting 

Python3

# For list of integers
lst1 = []
 
# For list of strings/chars
lst2 = []
 
lst1 = [int(item) for item in input("Enter \
                the list items : ").split()]
 
lst2 = [item for item in input("Enter \
                the list items : ").split()]
 
print(lst1)
print(lst2)

                    

Output: 

Python | Get a list as input from user

Last Updated : 28 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads