Search code examples
pythonlisttypeerrormultiplication

Python - How to get an integer from a list


I have an unknown list of numbers (the numbers get entered later in the program) and I am trying to find the largest one in the list, then store it in a variable so that I can do multiplication with it later. When I use max() I get an error saying "TypeError: can't multiply sequence by non-int of type 'list'" My code to find the largest number in the list is:

def adjacentElementsProduct(inputArray):
    input_list = [inputArray]
    numb1 = max(input_list)
    print(numb1)

My full code was

def adjacentElementsProduct(inputArray):
input_list = inputArray
numb1 = max(input_list)
print(numb1)
location = input_list.index(numb1)
if numb1 == input_list[-1]:
    test2 = input_list[location-1]
    small_list = [test2]
    numb3 = small_list[0]
    return numb1 * numb3
elif numb1 == input_list[0]:
    test1 = input_list[location+1]
    small_list = [test1]
    numb3 = small_list[0]
    return numb1 * numb3
else:
    test1 = input_list[location+1]
    test2 = input_list[location-1]
    greater_list = [test1, test2]
    numb2 = max(greater_list)
    return numb1 * numb2

Solution

  • The issue is that you are making a list within a list. You are passing the function a list, which you put inside brackets, thus creating a 2d list. Try this:

    def adjacentElementsProduct(inputArray):
        input_list = inputArray
        #or:
        #input_list = [inputArray]
        #numb1 = max(input_list[0])
        numb1 = max(input_list)
        print(numb1)