'how to read array elements from user in python
I am trying to read array elements as
4 #no. of elements to be read in array
1 2 3 4
what i have tried by referring other answers
def main():
n=int(input("how many number you want to enter:"))
l=[]
for i in range(n):
l.append(int(input()))
this works fine if i give input as
4 #no. of elements to be read
1
2
3
4
but if i try to give like
4 #no. of element to be read
1 2 3 4
I get error as:
ValueError: invalid literal for int() with base 10: '1 2 3 4'
Please help me with this
Solution 1:[1]
Since there's no input delimiters in Python, you should use split
and split the input that you've received from the user:
lst = your_input.split()
Solution 2:[2]
Your first approach is OK, for the second way use this:
n=int(input("how many number you want to enter:"))
l=map(int, input().split())[:n] # l is now a list of at most n integers
This will map
the function int
on the split parts (what split
gives) of the user input (which are 1
, 2
, 3
and 4
in your example.
It also uses slicing (the [:n]
after map
) to slice in case the user put more integers in.
Solution 3:[3]
The input()
function returns a string that the user enters. The int()
function expects to convert a number as a string to the corresponding number value. So int('3')
will return 3. But when you type in a string like 1 2 3 4
the function int()
does not know how to convert that.
You can either follow your first example:
n = int(input('How many do you want to read?'))
alist = []
for i in range(n):
x = int(input('-->'))
alist.append(x)
The above requires you to only enter a number at a time.
Another way of doing it is just to split the string.
x = input('Enter a bunch of numbers separated by a space:')
alist = [int(i) for i in x.split()]
The split()
method returns a list of numbers as strings excluding the spaces
Solution 4:[4]
n = input("how many number you want to enter :")
l=readerinput.split(" ")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Maroun |
Solution 2 | Reut Sharabani |
Solution 3 | Loupi |
Solution 4 | Rahul Saxena |