You can accept their input and convert it to an int
>>> size = int[input['Enter size of array: ']]
Enter size of array: 3
Then use this value within the range
function to iterate that many times. Doing so in a list comprehension you can repeatedly ask for input the same way.
>>> values = [int[input['Enter a value: ']] for _ in range[size]]
Enter a value: 3
Enter a value: 5
Enter a value: 7
>>> values
[3, 5, 7]
To do this in a more step-by-step manner you can use a for
loop
values = []
for _ in range[size]:
values.append[int[input['Enter a value: ']]]
If you just want them to enter a line of values, don't worry about asking how many there will be. You can use split[]
to tokenize the string on
whitespace [or whatever delimiter you pass in], then convert each value to an int
.
>>> values = [int[i] for i in input['Enter some values: '].split[]]
Enter some values: 3 5 7 8
>>> values
[3, 5, 7, 8]
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
We often encounter a situation when we need to take number/string as input from the user. In this article, we will see how to get as input a list from the user.
Examples:
Input : n = 4, ele = 1 2 3 4 Output : [1, 2, 3, 4] Input : n = 6, ele = 3 4 1 7 9 6 Output : [3, 4, 1, 7, 9, 6]
Code #1: Basic example
Python3
lst
=
[]
n
=
int
[
input
[
"Enter number of elements : "
]]
for
i
in
range
[
0
, n]:
ele
=
int
[
input
[]]
lst.append[ele]
print
[lst]
Output:
Code #2: With handling exception
Python3
try
:
my_list
=
[]
while
True
:
my_list.append[
int
[
input
[]]]
except
:
print
[my_list]
Output:
Code #3: Using map[]
Python3
n
=
int
[
input
[
"Enter number of elements : "
]]
a
=
list
[
map
[
int
,
input
[
"\nEnter the numbers : "
].strip[].split[]]][:n]
print
[
"\nList is - "
, a]
Output:
Code
#4: List of lists as input
Python3
lst
=
[ ]
n
=
int
[
input
[
"Enter number of elements : "
]]
for
i
in
range
[
0
, n]:
ele
=
[
input
[],
int
[
input
[]]]
lst.append[ele]
print
[lst]
Output:
Code #5: Using List Comprehension and Typecasting
Python3
lst1
=
[]
lst2
=
[]
lst1
=
[
int
[item]
for
item
in
input
[
"Enter the list items : "
].split[]]
lst2
=
[item
for
item
in
input
[
"Enter the list items : "
].split[]]
print
[lst1]
print
[lst2]
Output: