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

Question:

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:

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))
Asked By: beginner

||

Answers:

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.

Answered By: Code-Apprentice
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.