Open In App

Get a list as input from user in Python

Last Updated : 05 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 using Python.

Get list as input Using split() Method

The input() function can be combined with split() to accept multiple elements in a single line and store them in a list. The split() method separates input based on spaces and returns a list.

# Get user input and split it into a list
user_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.

a = []

# Get the number of elements
n = int(input("Enter the number of elements: "))

# Append elements to the list
for i in range(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 use map() to convert them to integers. Wrap map() in list() to store the result as a list

# Get user input, split it, and convert to integers
user_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 and input() into a single line for it be concise and quick.

# Get the number of elements
n = int(input("Enter the number of elements: "))

# Use list comprehension to get inputs
a = [input(f"Enter element {i+1}: ") for i in range(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.

# Get user input for a nested list
user_input = [x.split(",") for x in input("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.


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg