Python provides several ways to take a list as input in Python in a single line. Taking user input is a common task in Python programming, and when it comes to handling lists, there are several efficient ways to accomplish this in just a single line of code. In this article, we will explore four commonly used methods to take a list as input in Python, making your code more concise and readable.
Example:
Enter elements separated by space:11 12 13 14 15
[11, 12, 13, 14, 15]
How To Take List As Input In Python In Single Line?
Below, are the methods of How To Take a List As Input In Python In a Single Line.
- Using list comprehension
- Using the map() function
- Using list() and input().split()
- Using a generator expression
Take List As Input In Python In Single Line Using List Comprehension
In this example, the below code takes a space-separated list of user-input elements, converts them to integers, and stores them in the `user_list`, then prints the resulting list.
user_list = [int(x) for x in input("Enter elements separated by space:").split()]
print(user_list)
Output
Enter elements separated by space:11 12 13 14 15
[11, 12, 13, 14, 15]
Take List As Input In Python In Single Line Using the map() function
In this example, This code prompts the user to input space-separated elements, converts them to integers using `map()` and `int()`, and then prints the resulting list of integers.
user_list = list(map(int, input("Enter elements separated by space:").split()))
print(user_list)
Output
Enter elements separated by space:11 12 13 14 15
[11, 12, 13, 14, 15]
Take List As Input In Python In Single Line Using list() & input().split() directly
In this example, below code takes a space-separated list of user-input elements, converts each element to an integer using a generator expression, and stores the integers in the `user_list`, then prints the resulting list.
user_list = list(int(x) for x in input("Enter elements separated by space:").split())
print(user_list)
Output
Enter elements separated by space:11 12 13 14 15
[11, 12, 13, 14, 15]
Take List As Input In Python In Single Line Using a generator expression
In this example, This code prompts the user to input space-separated elements, converts each element to an integer using a generator expression, and then prints the resulting list of integers.
user_list = list(int(x) for x in input("Enter elements separated by space:").split())
print(user_list)
Output
Enter elements separated by space:11 12 13 14 15
[11, 12, 13, 14, 15]
Conclusion
In Python, there are multiple ways to take a list as input in just a single line of code. Whether you choose list comprehension, map(), direct list(), or a generator expression depends on your preference and specific use case. By incorporating these techniques into your code, you can enhance its readability and efficiency.