Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between int,input() and int(input())

I discovered that when listing an array, int,input is acceptable than int(input()). Can someone explain it to me what is the difference of this two and why is that the output?

when this is my code:

def Union(arr1, arr2):
    res = list(set(arr1) | set(arr2))
    return sorted(res)
 
arr1 = list(map(int(input("Enter first array: ").split())))
arr2 = list(map(int(input("Enter second array: ").split())))
print(Union(arr1, arr2))

It outputs:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Enter first array: 1 2 3
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    arr1 = list(map(int(input("Enter first array: ").split())))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

Compare to when I use this code

def Union(arr1, arr2):
    res = list(set(arr1) | set(arr2))
    return sorted(res)
 
arr1 = list(map(int,input("Enter first array: ").split()))
arr2 = list(map(int,input("Enter second array: ").split()))
print(Union(arr1, arr2))

>Solution :

Both of your solutions are doing a lot of things all in one line. Let’s break each line into smaller steps to see what it is doing.

We’ll start with

arr1 = list(map(int,input("Enter first array: ").split()))

Now let’s look at each piece individually:

number_string = input("Enter first array: ") # get input
number_strings = number_string.split()       # split input into a list
numbers = map(int, number_strings)           # convert input to numbers
number_list = list(numbers)                  # make it a list

Now let’s break down this one:

arr1 = list(map(int(input("Enter first array: ").split())))

The individual pieces look like this:

number_string = input("Enter first array: ") # get input
number_strings = number_string.split()       # split input into a list
number = int(number_strings)                 # convert an entire list to a number????

Now we can see why there is an error. You cannot convert a list to an int.

Often when you have errors or other issues, it is best to break a long statement into smaller pieces like this. That way you can see which of the smaller steps causes the problem.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading