How to Input a List in Python using For Loop
Using a for loop to take list input is a simple and common method. It allows users to enter multiple values one by one, storing them in a list. This approach is flexible and works well when the number of inputs is known in advance.
Let’s start with a basic way to input a list using a for loop in Python.
n = int(input("Number of elements: "))
a = []
# Use a for loop to take input from user
for i in range(n):
# Collect input for each element
val = input()
a.append(val)
print(a)
Output:
Number of elements: 4
1
2
3
4
['1', '2', '3', '4']
Explanation: We are first prompting the user to specify how many elements to enter. Then, the for loop runs n times each time taking input and appending it to the list a
.
Note: We can modify this code to input integers, floats or other types by using appropriate type casting.
Using List Comprehension
List comprehension offers a concise way to take multiple inputs in a single line and store them in a list. This approach is more efficient and reduces the need for explicit append()
calls, resulting in a more "Pythonic" approach.
n = int(input("number of elements: "))
a = [input() for i in range(n)]
print(a)
Output:
number of elements: 3
4
5
6
['4', '5', '6']
Explanation: This approach creates a list a
directly by iterating over a range using list comprehension.