Get a list as input from the user

Get a list as input from the user

Introduction

Now in day-to-day programming, we need to take numbers or strings as input. Now in Python, we can take input from the user by using the input keyword. Let us see how can we input a list from the user.

Example

Input: n = 8,  x = a b c d e f g h
Output:  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Input: n = 4, x = 1 2 3 4
Output: [1, 2, 3, 4]

Taking list as input from the user

Lists: In Python, just like java and c++, Lists are just like dynamic arrays. A list is a collection or pack of items. Lists are enclosed in square brackets i.e. [] and all its elements are separated by commas.

Code

l = []
 
n = int(input("Enter the number of elements: "))

for i in range(0, n):
    x = int(input())
    l.append(x)
     
print(l)

Output

Enter the number of elements: 6
1
2
3
4
5
6
[1, 2, 3, 4, 5, 6]

write your code here: Coding Playground

Taking list as input from the user with handling exceptions

Exceptions: In Python, when a cod is correct syntactically but gives an error while running, then exceptions are raised. Now, this error or the exception does not stop the execution of the program, the program still executes, but the exception will change the flow of the program.

Code

try:
l = []
while True:
l.append(int(input()))
except:
print(l)

Output

1
2
3
4
5
6
STOP

write your code here: Coding Playground

Taking a list as input from the user using the map

map(): In python, the map is a function. This method returns a map object of the results after applying this method to every item of iterable such as a list, tuple etc. This map object is an iterator.

Code

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

l = list(map(int,input("\nEnter the numbers: ").strip().split()))[:n]

print(l)

Output

Enter the number of elements: 4
Enter the numbers: 5 7 2 9
[5, 7, 2, 9]

write your code here: Coding Playground

Taking list of lists as input

Code

l = []
n = int(input())

for i in range(0, n):
x = [input(), int(input())]
l.append(x)

print(l)

Output

3
a
1
b
2
c
3
[['a', 1], ['b', 2], ['c', 3]]

write your code here: Coding Playground

Taking input by using List Comprehension and Typecasting

list comprehension: In python, list comprehension is used to execute some expression while iterating over each element of a list. It contains brackets that contain the expression, and that expression is executed for each of the elements of the list.

Code

l1 = []
l2 = []

l1 = [int(item) for item in input().split()]

l2 = [item for item in input().split()]

print(l1)
print(l2)

Output

1 2 3 4 5 6
A B C D E F

[1, 2, 3, 4, 5, 6]
['A', 'B', 'C', 'D', 'E', 'F']

write your code here: Coding Playground