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 take a list as input from the user usingPython.
Get list as inputUsingsplit()
Method
Theinput()
function can be combined withsplit()
to accept multiple elements in a single line and store them in a list. Thesplit()
method separates input based on spaces and returns a list.
Python# Get user input and split it into a listuser_input=input("Enter elements separated by space: ").split()print("List:",user_input)
Output:
1 2 3 4 5
List: ['1', '2', '3', '4', '5']
Let's see some other methods to get a list as input from user in Python
Get list as input Using a Loop
This method lets users add one element at a time, it is ideal when the size of the list is fixed or predefined. Here we are using a loop to repeatedly take input and append it to the list.
Pythona=[]# Get the number of elementsn=int(input("Enter the number of elements: "))# Append elements to the listforiinrange(n):element=input(f"Enter element{i+1}: ")a.append(element)print("List:",a)
Output:
Enter the number of elements: 3
Enter element 1: Python
Enter element 2 : is
Enter element 3: fun
List: ['Python', 'is', 'fun']
Get list as input Using map()
If numeric inputs are needed we can usemap()
to convert them to integers. Wrapmap()
inlist()
to store the result as a list
Python# Get user input, split it, and convert to integersuser_input=list(map(int,input("Enter numbers separated by space: ").split()))print("List:",user_input)
Output:
1 2 3 4 5
List: [1, 2, 3, 4, 5]
Using List Comprehension for Concise Input
List comprehension provides a compact way to create a list from user input. Combines a loop andinput()
into a single line for it be concise and quick.
Python# Get the number of elementsn=int(input("Enter the number of elements: "))# Use list comprehension to get inputsa=[input(f"Enter element{i+1}: ")foriinrange(n)]print("List:",a)
Output:
Enter the number of elements: 3
Enter element 1: dog
Enter element 2: cat
Enter element 3: bird
List: ['dog', 'cat', 'bird']
Accepting a Nested List Input
We can also accept a nested list by splitting the input on custom delimiters like semicolons.
Python# Get user input for a nested listuser_input=[x.split(",")forxininput("Enter nested list (use commas and semicolons): ").split(";")]print("Nested List:",user_input)
Output:
1,2,3;4,5;6,7,8
Nested List: [['1', '2', '3'], ['4', '5'], ['6', '7', '8']]
Explanation:
- The outer
split(";")
separates sublists. - The inner
split(",")
creates elements in each sublist.

input() in Python

Get a list as input from user in Python