Skip to content

How to take list input in Python in single line | Example code

  • by

To take list input in Python in a single line use input() function and split() function. Where the input() function accepts a string, integer, and character input from a user, and the split() function splits an input string by space.

# Method 1: Using list comprehension
input_list = [int(x) for x in input("Enter space-separated elements: ").split()]

# Method 2: Using map function with list comprehension
input_list = list(map(int, input("Enter space-separated elements: ").split()))

# Method 3: Using map function with lambda function
input_list = list(map(lambda x: int(x), input("Enter space-separated elements: ").split()))

The above code will prompt the user to enter space-separated elements, and it will convert those elements into integers and store them in the input_list variable. If you want to take elements of other data types, you can adjust the int() function in the code accordingly. For example, if you want to take string inputs, you can remove the int() function.

Example take list input in Python in a single line

Simple example code.

lst = input('Type separated by space: ').split()

# print list
print('list: ', lst)


How to take list input in Python in single line

How to read an array of integers from a single line of input in python 3?

Answer: Use the map() function along with the input and split function. Using int to Read an array of integers only.

The following snippet will map the single-line input separated by white space into a list of integers.

lst = list(map(int, input("Type number with space: ").split()))

# print list
print('list: ', lst)


Type number with space: 1 2 3
list: [1, 2, 3]

Do comment if you have any doubts or suggestions on this Python list input topic

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.

Leave a Reply

Your email address will not be published. Required fields are marked *