Search code examples
pythonobjectinttypeerroriterable

Getting error "TypeError: 'int' object is not iterable"


    matrix = [
    [3,6,3],
    [6,8,5],
    [8,5,9],
]

for lists in matrix:
    for numbers in lists:
        print(max(numbers)

I want to make a code to find out the largest number in a Matrix, but however I get this strange error which I am unable to figure it out. Here's the error

  File "C:/Users/AK/PycharmProjects/pythonProject2/main.py", line 9, in <module>
    print(max(numbers))
TypeError: 'int' object is not iterable

What can I try to resolve this?


Solution

  • Your confusion appears to be coming from the semantics of your variable names. For example, take a look at this:

    for lists in matrix:
    

    The matrix you have is a "list of lists", this is true. So then each item in that matrix shouldn't be called a "lists", it should be called a "list". Let's see where that takes us:

    for list in matrix:
        for numbers in list:
    

    Same thing. Each element is not a "numbers", it's a "number":

    for list in matrix:
        for number in list:
            print(max(number))
    

    And now the problem becomes clear. It doesn't make sense to find the maximum of a "number". Because it's only one number. You can print the number:

    for list in matrix:
        for number in list:
            print(number)
    

    But what you appear to be trying to achieve is to find the maximum in each list. Falling back on the semantics that are now more clear, you'd do that on the list object:

    for list in matrix:
        print(max(list))