Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Get a list as input from user
In this article, we will see how to ask the user to enter elements of a list and create the list with those entered values. Python provides several approaches to collect user input and build lists dynamically.
Using Loop with input() and append()
The most straightforward approach is to ask for the number of elements first, then collect each element individually using a loop ?
numbers = []
# Input number of elements
n = int(input("Enter number of elements in the list : "))
# iterating till the range
for i in range(0, n):
print("Enter element No-{}: ".format(i+1))
elm = int(input())
numbers.append(elm) # adding the element
print("The entered list is: \n", numbers)
Enter number of elements in the list : 4 Enter element No-1: 7 Enter element No-2: 45 Enter element No-3: 1 Enter element No-4: 74 The entered list is: [7, 45, 1, 74]
Using map() with Split Input
Another approach is to ask the user to enter all values in a single line separated by commas. Here we use the map() function to convert the inputs into a list ?
# Input number of elements
n = int(input("Enter number of elements in the list : "))
# Enter elements separated by comma
numbers = list(map(int, input("Enter the numbers : ").strip().split(',')))[:n]
print("The entered list is: \n", numbers)
Enter number of elements in the list : 4 Enter the numbers : 12,45,65,32 The entered list is: [12, 45, 65, 32]
Creating List of Lists
We can also create nested lists by using the input() function multiple times. This approach allows us to create a list where each element is itself a list containing mixed data types ?
nested_list = []
# Input number of elements
n = int(input("Enter number of elements in the list : "))
# Each sublist has two elements
for i in range(0, n):
print("Enter element No-{}: ".format(i + 1))
ele = [input(), int(input())]
nested_list.append(ele)
print("The entered list is: \n", nested_list)
Enter number of elements in the list : 2 Enter element No-1: 'Mon' 3 Enter element No-2: 'Tue' 4 The entered list is: [["'Mon'", 3], ["'Tue'", 4]]
Comparison of Methods
| Method | Input Style | Best For |
|---|---|---|
| Loop + append() | One element per line | Simple validation, mixed types |
| map() + split() | All elements in one line | Quick input, same data type |
| Nested loops | Multiple inputs per element | Complex data structures |
Conclusion
Use the loop approach for collecting elements individually with validation. Use map() with split() for quick single-line input when all elements are the same type.
