1

So I just wanted to know the reason and cause of error I am getting in order to get a better understanding of python.

Here is what I have tried.

Code snippet #1

x,y=int(input()),int(input())
print(x,y)
print(type(x))
print(type(y))

So I get the output -

4
6
4 6
<class 'int'>
<class 'int'>

I am fine with the output, but what bugs me is why I can't use it in the manner like -

Code snippet #2

x,y= int(input().split('-'))
print(x,y)
print(type(x))
print(type(y))

So here, on wrapping input().split() inside int(), it throws an error as :

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

My Doubt

I just want to know why I cannot wrap int() inside input().split() ? Is there an alternate way to do it? Or if it's not allowed please explain why.

2
  • 2
    Because split returns a list. You can't cast list to int. You should use list comprehension or map to make it work. Commented Feb 12, 2019 at 7:15
  • @dyukha you are correct. I just came across the concept of map and found what you said. Commented Feb 12, 2019 at 7:17

2 Answers 2

2

From docs.python.org:

str.split() returns a list of the words in str

You can not turn a list to a int

You can try this way:

(x, y) = (int(x) for x in input().split('-'))
print(x, y)
print(type(x))
print(type(y))
Sign up to request clarification or add additional context in comments.

1 Comment

Your solution is also acceptable and an alternate way to get the job done.Appreciate your help.
1

Okay so if you want to take multiple inputs in a single line and also convert it into desired data type, you can use map() to achieve it.

Code snippet #3

x,y,z=map(int,input().strip().split())
print(x,y,z)
print(type(x))
print(type(y))
print(type(z))

So your output will look like this -

2 3 4
2 3 4
<class 'int'>
<class 'int'>
<class 'int'>

And as @dyukha pointed out correctly the reason you cannot wrap input().split() inside int() is because split() returns a list and we cannot cast list to int data type.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.