Use an input() function with split() function to split an input string by space and splits a string into a list to create a list from user input in Python.
Example create a list from user input in Python
Simple example code gets a list of numbers as input from a user.
input_string = input('Enter elements separated by space: ')
user_list = input_string.split()
# print list
print('list: ', user_list)
Output:
Another example
Using for loop and range function.
listA = []
# Input number of elemetns
n = int(input("Enter number of elements in the list : "))
for i in range(0, n):
print("Enter element No-{}: ".format(i + 1))
listA.append(input()) # adding the element
print("The entered list is: \n", listA)
Output:
Enter number of elements in the list : 2
Enter element No-1:
A
Enter element No-2:
1
The entered list is:
[‘A’, ‘1’]
With map
User to enter the values continuously but separated by space. Here we use the map function together with the inputs into a list.
listA = []
# Input number of elemetns
n = int(input("List elements: "))
listA = list(map(int, input("Numbers : ").strip().split()))[:n]
print(listA)
Output:
List elements: 2
Numbers: 1 2
[1, 2]
Do comment if you have any doubts or suggestions on this Python List input code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.