Int object is not iterable python ошибка

You are trying to loop over in integer; len() returns one.

If you must produce a loop over a sequence of integers, use a range() object:

for i in range(len(str_list)):
    # ...

By passing in the len(str_list) result to range(), you get a sequence from zero to the length of str_list, minus one (as the end value is not included).

Note that now your i value will be the incorrect value to use to calculate an average, because it is one smaller than the actual list length! You want to divide by len(str_list):

return str_sum / len(str_list)

However, there is no need to do this in Python. You loop over the elements of the list itself. That removes the need to create an index first:

for elem in str_list
    str_sum += len(elem)

return str_sum / len(str_list)

All this can be expressed in one line with the sum() function, by the way:

def str_avg(s):
    str_list = s.split()
    return sum(len(w) for w in str_list) / len(str_list)

I replaced the name str with s; better not mask the built-in type name, that could lead to confusing errors later on.

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

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!

The Python TypeError: 'int' object is not iterable is an exception that occurs when trying to loop through an integer value. In Python, looping through an object requires the object to be “iterable”. Since integers are not iterable objects, looping over an integer raises the TypeError: 'int' object is not iterable exception.

Python TypeError: Int Object Is Not Iterable Example

Here’s an example of a Python TypeError: 'int' object is not iterable thrown when trying iterate over an integer value:

myint = 10

for i in myint:
    print(i)

In the above example, myint is attempted to be iterated over. Since myint is an integer and not an iterable object, iterating over it raises a TypeError: 'int' object is not iterable:

File "test.py", line 3, in <module>
    for i in myint:
TypeError: 'int' object is not iterable

How to Fix TypeError: Int Object Is Not Iterable

In the above example, myint cannot be iterated over since it is an integer value. The Python range() function can be used here to get an iterable object that contains a sequence of numbers starting from 0 and stopping before the specified number.

Updating the above example to use the range() function in the for loop fixes the error:

myint = 10

for i in range(myint):
    print(i)

Running the above code produces the following output as expected:

0
1
2
3
4
5
6
7
8
9

How to Avoid TypeError: Int Object Is Not Iterable

The Python TypeError: 'int' object is not iterable error can be avoided by checking if a value is an integer or not before iterating over it.

Using the above approach, a check can be added to the earlier example:

myint = 10

if isinstance(myint, int):
    print("Cannot iterate over an integer")
else:
    for i in myint:
        print(i)

A try-except block can also be used to catch and handle the error if the type of object not known beforehand:

myint = 10

try:
    for i in myint:
        print(i)
except TypeError:
    print("Object must be an iterable")

Surrounding the code in try-except blocks like the above allows the program to continue execution after the exception is encountered:

Object must be an iterable

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

So, you have encountered the exception, i.e., TypeError: ‘int’ object is not iterable. In the following article, we will discuss type errors, how they occur and how to resolve them. You can also check out our other articles on TypeError here.

What is a TypeError?

The TypeError occurs when you try to operate on a value that does not support that operation. Let’s see an example of the TypeError we are getting.

number_of_emp = int(input("Enter the number of employees:"))

for employee in number_of_emp:
	name = input("employee name:")
	dept = input("employee department:")
	sal = int(input("employee salary:"))

TypeError: 'int' object is not iterable

TypeError: ‘int’ object is not iterable

Before we understand why this error occurs, we need to have some basic understanding of terms like iterable, dunder method __iter__.

Iterable

Iterable are objects which generate an iterator. For instance, standard python iterable are list, tuple, string, and dictionaries.

All these data types are iterable. In other words, they can be iterated over using a for-loop. For instance, check this example.

from pprint import pprint

names = ['rohan','sunny','ramesh','suresh']
products = {
	'soap':40,
	'toothpaste':100,
	'oil':60,
	'shampoo':150,
	'hair-gel':200
}
two_tuple = (2,4,6,8,9,10,12,14,16,18,20)
string = "This is a random string."

for name in names:
	print(name,end=" ")

print("n")

for item,price in products.items():
	pprint(f"Item:{item}, Price:{price}")

print("n")

for num in two_tuple:
	print(num,end=" ")

print("n")

for word in string:
	print(word,end=" ")

Outputs of different iterables

Outputs of different iterables

[Solved] typeerror: unsupported format string passed to list.__format__

__iter__ dunder method

__iter__ dunder method is a part of every data type that is iterable. In other words, for any data type, iterable only if __iter__ method is contained by them. Let’s understand this is using some examples.

For iterable like list, dictionary, string, tuple:

You can check whether __iter__ dunder method is present or not using the dir method. In the output image below, you can notice the __iter__ method highlighted.

__iter__ method present in list data type

__iter__ method present in list data type

Similarly, if we try this on int datatype, you can observe that __iter__ dunder method is not a part of int datatype. This is the reason for the raised exception.

__iter__ method not a part of int datatype

__iter__ method not a part of int datatype

How to resolve this error?

Solution 1:

Instead of trying to iterate over an int type, use the range method for iterating, for instance.

number_of_emp = int(input("Enter the number of employees:"))

for employee in range(number_of_emp):
	name = input("employee name:")
	dept = input("employee department:")
	sal = int(input("employee salary:"))

TyperError resolved using the range method

TypeError resolved using the range method.

Solution 2:

You can also try using a list datatype instead of an integer data type. Try to understand your requirement and make the necessary changes.

random.choices ‘int’ object is not iterable

This error might occur if you are trying to iterate over the random module’s choice method. The choice method returns values one at a time. Let’s see an example.

import random

num_list = [1,2,3,4,5,6,7,8,9]

for i in random.choice(num_list):
	print(i)

random.choices ‘int’ object is not iterable

random.choices ‘int’ object is not iterable

Instead, you should try something like this, for instance, using a for loop for the length of the list.

import random

num_list = [1,2,3,4,5,6,7,8,9]

for i in range(len(num_list)):
 	print(random.choice(num_list))

Iterating over random.choice

Iterating over random.choice

jinja2 typeerror ‘int’ object is not iterable

Like the above examples, if you try to iterate over an integer value in the jinja template, you will likely face an error. Let’s look at an example.

{% for i in 11 %}
  <p>{{ i }}</p>
{% endfor %}

The above code tries to iterate over integer 11. As we explained earlier, integers aren’t iterable. So, to avoid this error, use an iterable or range function accordingly.

[Fixed] io.unsupportedoperation: not Writable in Python

FAQs on TypeError: ‘int’ object is not iterable

Can we make integers iterable?

Although integers aren’t iterable but using the range function, we can get a range of values till the number supplied. For instance:
num = 10
print(list(range(num)))

Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

How to solve self._args = tuple(args) TypeError ‘int’ object is not iterable problem?

This is a condition when the function accepts arguments as a parameter. For example, multiprocessing Process Process(target=main, args=p_number) here, the args accepts an iterable tuple. But if we pass an integer, it’ll throw an error.

How to solve TypeError’ int’ object is not iterable py2exe?

py2exe error was an old bug where many users failed to compile their python applications. This is almost non-existent today.

Conclusion

In this article, we tried to shed some light on the standard type error for beginners, i.e. ‘int’ object is not iterable. We also understood why it happens and what its solutions are.

Other Errors You Might Encounter

  • [Solved] typeerror: unsupported format string passed to list.__format__

    [Solved] typeerror: unsupported format string passed to list.__format__

    May 31, 2023

  • Solving ‘Remote End Closed Connection’ in Python!

    Solving ‘Remote End Closed Connection’ in Python!

    by Namrata GulatiMay 31, 2023

  • [Fixed] io.unsupportedoperation: not Writable in Python

    [Fixed] io.unsupportedoperation: not Writable in Python

    by Namrata GulatiMay 31, 2023

  • [Fixing] Invalid ISOformat Strings in Python!

    [Fixing] Invalid ISOformat Strings in Python!

    by Namrata GulatiMay 31, 2023

Понравилась статья? Поделить с друзьями:
  • Indesit wiun 102 сброс ошибок
  • Indesit wiun 102 ошибки расшифровка
  • Indesit wiun 102 ошибка f08
  • Indesit wiun 102 коды ошибок мигает
  • Indesit wiun 100 ошибка f08