Argument of type int is not iterable ошибка

I am getting this error when I run my program and I have no idea why. The error is occurring on the line that says «if 1 not in c:»

Code:

matrix = [
    [0, 0, 0, 5, 0, 0, 0, 0, 6],
    [8, 0, 0, 0, 4, 7, 5, 0, 3],
    [0, 5, 0, 0, 0, 3, 0, 0, 0],
    [0, 7, 0, 8, 0, 0, 0, 0, 9],
    [0, 0, 0, 0, 1, 0, 0, 0, 0],
    [9, 0, 0, 0, 0, 4, 0, 2, 0],
    [0, 0, 0, 9, 0, 0, 0, 1, 0],
    [7, 0, 8, 3, 2, 0, 0, 0, 5],
    [3, 0, 0, 0, 0, 8, 0, 0, 0],
    ]
a = 1
while a:
     try:
        for c, row in enumerate(matrix):
            if 0 in row:
                print("Found 0 on row,", c, "index", row.index(0))
                if 1 not in c:
                    print ("t")
    except ValueError:
         break

What I would like to know is how I can fix this error from happening an still have the program run correctly.

Thanks in advance!

In Python, the error TypeError: argument of type ‘int’ is not iterable occurs when the membership operator (in, not in) is used to validate the membership of a value in non iteratable objects such as list, tuple, dictionary. The membership operator can be used to verify memberships in variables such as strings, numbers, tuples and dictionary.

The membership operator (in, not in) in Python is used to test whether or not the given value exists in another variable. The operator searches the value in an iterable object. The error “TypeError: argument of type ‘int’ is not iterable” is due to the search of value in a non-iterable object.

Through this article, we can see what this error is, how this error can be solved. This type error is due to missing of an non-iterable object in the membership operator. The error would be thrown as like below.

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print x in y
TypeError: argument of type 'int' is not iterable
[Finished in 0.1s with exit code 1]

Different Variation of the error

In different contexts the “TypeError: argument of type ‘int’ is not iterable” error is thrown in various forms in python. The numerous variations of TypeError are given below.

TypeError: argument of type 'int' is not iterable
TypeError: argument of type 'float' is not iterable
TypeError: argument of type 'bool' is not iterable
TypeError: argument of type 'complex' is not iterable
TypeError: argument of type 'long' is not iterable
TypeError: argument of type 'NoneType' is not iterable
TypeError: argument of type 'type' is not iterable

Root Cause

The membership operator searches for a value in an iterable object such as list, tuple, dictionary. If the value presents in an iterable object, returns true, otherwise it returns false. If you are looking for a value in non-iterable object such as int, float, boolean, python can not identify the presents of the value. In this case the python interpreter will throw that error.

How to reproduce this issue

If you are looking for a value in non-iterable object such as int, float, boolean, the python interpreter will throw this error. The code below searches an integer value in another integer value. This error will be thrown, as an integer value is not an iterable entity.

x = 4
y = 4
print x in y

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print x in y
TypeError: argument of type 'int' is not iterable

Solution 1

If the membership operator (in, not in) is used, the value present in an iterable object such as list, tuple, or dictionary should be checked. Verify that the program looks for iterable objects. In the membership operator, the wrong variable is used, or the wrong value is given in the variable.

x = 4
y = [4, 5]
print x in y

Output

True

Solution 2

If you want to check a value with another value, you should not use the Membership Operator. Instead, the logical operator is used to compare two values. The logical operator in python will compare two values. The code below shows how to use comparison of the value.

x = 4
y = 4
print x == y

Output

True

Solution 3

If the membership operator variable contains None value, the membership operator would not be able to iterate that value. Membership operator throws “TypeError: the ‘NoneType’ argument is not iterable” error. Either Null check must be performed or assigned with an iterable object as the default.

x = 4
y = None
print x in y

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print x in y
TypeError: argument of type 'NoneType' is not iterable

Solution

x = 4
y = []
print x in y

Output

False

Solution 4

If the type of the value is used in the membership operator, python interpreter will throw “TypeError: type ‘type’ argument is not iterable” error. The value presents check can not be performed on the type of the object. It is because of error in typing. The types such as list, tuple, dict are to be modified to functions such as list(), tuple(), dict().

x = 4
y = list
print x in y

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print x in y
TypeError: argument of type 'type' is not iterable

Solution

x = 4
y = list()
print x in y

Output

False

Int Object is Not Iterable – Python Error [Solved]

If you are running your Python code and you see the error “TypeError: ‘int’ object is not iterable”, it means you are trying to loop through an integer or other data type that loops cannot work on.

In Python, iterable data are lists, tuples, sets, dictionaries, and so on.

In addition, this error being a “TypeError” means you’re trying to perform an operation on an inappropriate data type. For example, adding a string with an integer.

Today is the last day you should get this error while running your Python code. Because in this article, I will not just show you how to fix it, I will also show you how to check for the __iter__ magic methods so you can see if an object is iterable.

How to Fix Int Object is Not Iterable

If you are trying to loop through an integer, you will get this error:

count = 14

for i in count:
    print(i)
# Output: TypeError: 'int' object is not iterable

One way to fix it is to pass the variable into the range() function.

In Python, the range function checks the variable passed into it and returns a series of numbers starting from 0 and stopping right before the specified number.

The loop will now run:

count = 14

for i in range(count):
    print(i)
    
# Output: 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# 11
# 12
# 13

Another example that uses this solution is in the snippet below:

age = int(input("Enter your age: "))

for num in range(age):
    print(num)

# Output: 
# Enter your age: 6
# 0
# 1
# 2
# 3
# 4
# 5

How to Check if Data or an Object is Iterable

To check if some particular data are iterable, you can use the dir() method. If you can see the magic method __iter__, then the data are iterable. If not, then the data are not iterable and you shouldn’t bother looping through them.

perfectNum = 7

print(dir(perfectNum))

# Output:['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', 
# '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

The __iter__ magic method is not found in the output, so the variable perfectNum is not iterable.

jerseyNums = [43, 10, 7, 6, 8]

print(dir(jerseyNums))

# Output: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

The magic method __iter__ was found, so the list jerseyNums is iterable.

Conclusion

In this article, you learned about the “Int Object is Not Iterable” error and how to fix it.

You were also able to see that it is possible to check whether an object or some data are iterable or not.

If you check for the __iter__ magic method in some data and you don’t find it, it’s better to not attempt to loop through the data at all since they’re not iterable.

Thank you for reading.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

So you’re getting the TypeError: argument of type ‘int’ is not iterable error message. I came across this issue when calling an api, extracting some data from a json object, and trying to determine if I needed to do something with that info.

Bite Size Soln for Those in a Rush

In short, you’re trying to find whether a substring exists in an integer. Make sure to cast your ints to strings and you should be able to continue on your way. Now, if you’d like a more detailed explanation, continue on.

My Setup

Python 3.x
macOS

Are you having issues with Python locally? This article might help you out.

The Issue

You are inadvertently trying to determine if a substring is in an integer! Let’s recreate it in a line or two.

word = 'stuff'
blur = 12344566
word in blur

You should be greeted with the ugly, “TypeError: argument of type ‘int’ is not iterable” message.

The Solution

Cast, Cast, Cast.

word = 'stuff'
blur = 12344566
word in str(blur)

A More Realistic Example

This will output false successfully telling you whether stuff can be found within the now string ‘12344566’. And now for a more realistic example.

array = ['Foo','Bar', 1]
for element in array:
    print(element)
    if 'sandwich' in element:
        print('Found the sandwich') 

Here we can see all elements of the array are printed because the error occurs on the third element. One will never find a string in an int. You can avoid checking types and error handling by wrapping element in str() to cast it as a string in case we come across any unruly data types.

array = ['Foo','Bar', 1]
for element in array:
    print(element)
    if 'sandwich' in str(element):
        print('Found the sandwich') 

The problem is gone. We also never find the sandwich. Happy coding!

Integers and iterables are distinct objects in Python. An integer stores a whole number value, and an iterable is an object capable of returning elements one at a time, for example, a list. If you try to iterate over an integer value, you will raise the error “TypeError: ‘int’ object is not iterable”. You must use an iterable when defining a for loop, for example, range(). If you use a function that requires an iterable, for example, sum(), use an iterable object as the function argument, not integer values.

This tutorial will go through the error in detail. We will go through two example scenarios and learn how to solve the error.


Table of contents

  • TypeError: ‘int’ object is not iterable
  • Example #1: Incorrect Use of a For Loop
    • Solution
  • Example #2: Invalid Sum Argument
    • Solution
  • Summary

TypeError: ‘int’ object is not iterable

TypeError occurs in Python when you try to perform an illegal operation for a specific data type. For example, if you try to index a floating-point number, you will raise the error: “TypeError: ‘float’ object is not subscriptable“. The part ‘int’ object is not iterable tells us the TypeError is specific to iteration. You cannot iterate over an object that is not iterable. In this case, an integer, or a floating-point number.

An iterable is a Python object that you can use as a sequence. You can go to the next item in the sequence using the next() method.

Let’s look at an example of an iterable by defining a dictionary:

d = {"two": 2, "four":4, "six": 6, "eight": 8, "ten": 10}

iterable = d.keys()

print(iterable)
dict_keys(['two', 'four', 'six', 'eight', 'ten'])

The output is the dictionary keys, which we can iterate over. You can loop over the items and get the values using a for loop:

for item in iterable:

    print(d[item])

Here you use item as the index for the key in the dictionary. The following result will print to the console:

2
4
6
8
10

You can also create an iterator to use the next() method

d = {"two": 2, "four":4, "six": 6, "eight": 8, "ten": 10} 

iterable = d.keys()

iterator = iter(iterable)

print(next(iterator))

print(next(iterator))
two

four

The code returns the first and second items in the dictionary. Let’s look at examples of trying to iterate over an integer, which raises the error: “TypeError: ‘int’ object is not iterable”.

Example #1: Incorrect Use of a For Loop

Let’s consider a for loop where we define a variable n and assign it the value of 10. We use n as the number of loops to perform: We print each iteration as an integer in each loop.

n = 10

for i in n:

    print(i)
TypeError                                 Traceback (most recent call last)
      1 for i in n:
      2     print(i)
      3 

TypeError: 'int' object is not iterable

You raise the error because for loops are used to go across sequences. Python interpreter expects to see an iterable object, and integers are not iterable, as they cannot return items in a sequence.

Solution

You can use the range() function to solve this problem, which takes three arguments.

range(start, stop, step)

Where start is the first number from which the loop will begin, stop is the number at which the loop will end and step is how big of a jump to take from one iteration to the next. By default, start has a value of 0, and step has a value of 1. The stop parameter is compulsory.

n = 10

for i in range(n):

   print(i)
0
1
2
3
4
5
6
7
8
9

The code runs successfully and prints each value in the range of 0 to 9 to the console.

Example #2: Invalid Sum Argument

The sum() function returns an integer value and takes at most two arguments. The first argument must be an iterable object, and the second argument is optional and is the first number to start adding. If you do not use a second argument, the sum function will add to 0. Let’s try to use the sum() function with two integers:

x = 2

y = 6

print(sum(x, y))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
1 print(sum(x,y))

TypeError: 'int' object is not iterable

The code is unsuccessful because the first argument is an integer and is not iterable.

Solution

You can put our integers inside an iterable object to solve this error. Let’s put the two integers in a list, a tuple, a set and a dictionary and then use the sum() function.

x = 2

y = 6

tuple_sum = (x, y)

list_sum = [x, y]

set_sum = {x, y}

dict_sum = {x: 0, y: 1}

print(sum(tuple_sum))

print(sum(list_sum))

print(sum(set_sum))

print(sum(dict_sum))
8
8
8
8

The code successfully runs. The result remains the same whether we use a tuple, list, set or dictionary. By default, the sum() function sums the key values.

Summary

Congratulations on reading to the end of this tutorial. The error “TypeError: ‘int’ object is not iterable” occurs when you try to iterate over an integer. If you define a for loop, you can use the range() function with the integer value you want to use as the stop argument. If you use a function that requires an iterable, such as the sum() function, you must put your integers inside an iterable object like a list or a tuple.

For further reading on the ‘not iterable’ TypeError go to the articles:

  • How to Solve Python TypeError: ‘NoneType’ object is not iterable.
  • How to Solve Python TypeError: ‘method’ object is not iterable.

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Возможно, вам также будет интересно:

  • Arerr 9388 ошибка аутентификации
  • Arena of valor ошибка 554827811
  • Are you writing your essay at the moment найти ошибку
  • Are you welsh ошибка
  • Are you older of your brother где ошибка

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии