We often encounter a situation when we need to take number/string as input from the user. In this article, we will see how to get as input a list from the user.
Examples:
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]
Code #1: Basic example
# creating an empty listlst = [] # number of elemetns as inputn = int(input("Enter number of elements : ")) # iterating till the rangefor i in range(0, n): ele = int(input()) lst.append(ele) # adding the element print(lst) |
Output:
Code #2: With handling exception
# try block to handle the exceptiontry: my_list = [] while True: my_list.append(int(input())) # if the input is not-integer, just print the listexcept: print(my_list) |
Output:
Code #3: Using map()
# number of elementsn = 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:
Code #4: List of lists as input
lst = [ ]n = int(input("Enter number of elements : ")) for i in range(0, n): ele = [input(), int(input())] lst.append(ele) print(lst) |
Output:
Code #5: Using List Comprehension and Typecasting
# For list of integerslst1 = [] # For list of strings/charslst2 = [] 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:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


