Skip to main content

Solve TypeError: ‘int’ object is not iterable in Python Gorakh Gupta The Crazy Programmer

Whenever we are writing any programs and then we encounter any error. The amount of frustration we got at that time is so much higher. So I have got a solution for you.

Today in this article we are going to discuss the error typeerror: ‘int’ object is not iterable.

We will discuss why we get this error and what are some possible solutions for this error. Please make sure to read till the end to save a lot of time in debugging this error.

First, let’s understand what the term ‘iterable’ means?

Iterable is something from which we can take values one by one and use them accordingly. For example whenever we are using a loop to iterate over a list or over a tuple then the loop is working as an iterable. It gives a single element at a time to process it.

In other terms, you can think of iterable as a container from which we get a single item at a time. And it will give the items as instructed.

For example:

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

when we run this code in the terminal we get the output:

0
1
2
3
4

In the above example, we can see that the range() functions return a list of numbers, and variable I is working as a container. It gives a single value at a time and prints it.

Now we will get to know why this error occurs and we will check how we can eliminate those errors..

Reasons for Error

Case 1:

Suppose you are writing a program in which there is a list of railway station names is given. You are trying to iterate through the list and print all the station names in uppercase order. You have used a loop to get this work done.

For example:

station_names = ['New Delhi', 'Lucknow', 'Patna', 'GorakhPur']

for num in len(station_names):
    station_uppercase = station_names[num].upper()
    print(station_uppercase)

When we run this program in our terminal then we will get an error like this.

Output:

Traceback (most recent call last):

  File “c:\Users\ASUS\Desktop\Geeksgyan Work\test.py”, line 3, in <module>

    for num in len(station_names):

TypeError: ‘int’ object is not iterable

As it is mentioned in the output itself that in line no. 3 we have got the error.

We got this error because we are trying to iterate values from a single integer value which is not possible. We know that len() function returns a value as an integer. So it cannot be iterated to get values. We can iterate those items only which is supposed to be a container, which means they contain a bunch of values as in list, tuples, etc.

Case 2:

Suppose there is a string given. We want to change alternate cases of character. Means lower and upper case in alternate order. We will do it by using a loop as demonstrated in the example below.

Example:

string = 'abcdefghij'

new_string = ''
for char in len(string):
    if (char % 2 != 0):
        new_string = new_string + string[char].upper()
    else:
        new_string = new_string + string[char]

print(f"After alternating case changes : {new_string}")

When we try to run it in our terminal then we will encounter the error: ‘int’ object is not iterable.

Output:

PS C:\Users\ASUS\Desktop\Geeksgyan Work> python -u “c:\Users\ASUS\Desktop\Geeksgyan Work\test.py”

Traceback (most recent call last):

  File “c:\Users\ASUS\Desktop\Geeksgyan Work\test.py”, line 4, in <module>

    for char in len(string):

TypeError: ‘int’ object is not iterable

Here the same error occurs because we are trying to iterate from an integer.

Sometimes these errors are very hard to get recognized and we spent some hours debugging our code to find the error.

Solutions for Error

As we know we are getting this error because we are trying to iterate that object which is not iterable. So we have to work on things that can make that object iterable.

We can see that using the range() function in loops solves the error because we know that range() function returns a container or a list of things in which we can iterate the values one by one and we can process it accordingly.

After using range() function in the loop, the error will be resolved and we will successfully be able to run our programs and we will see the desired output.

Case 1 Solution:

station_names = ['New Delhi', 'Lucknow', 'Patna', 'GorakhPur']

for num in range(len(station_names)):
    station_uppercase = station_names[num].upper()
    print(station_uppercase)

Output:

PS C:\Users\ASUS\Desktop\Geeksgyan Work> python -u “c:\Users\ASUS\Desktop\Geeksgyan Work\test.py”

NEW DELHI

LUCKNOW

PATNA

GORAKHPUR

We can see that our program runs successfully.

After we use the range function, then it returns an iterable and then our ‘num’ variable goes through that iterable and takes the values one at a time and convert it to upper case and then print the value.

That is how the iterable in as program works.

Case 2 Solution:

string = 'abcdefghij'

new_string = ''
for char in range(len(string)):
    if (char % 2 != 0):
        new_string = new_string + string[char].upper()
    else:
        new_string = new_string + string[char]

print(f"After alternating case changes : {new_string}")

Output:

PS C:\Users\ASUS\Desktop\Geeksgyan Work> python -u “c:\Users\ASUS\Desktop\Geeksgyan Work\test.py”

After alternating case changes : aBcDeFgHiJ

We can see that the program runs successfully after using the range() function in the code. It eliminates the error and gives the desired output.

Whenever this error occurs, the first thing you have to do is to find if there are any loops in the program, try to dry run the program and check if you are getting the output or not. Check whether you are trying to iterate a value that cannot be iterated. And you will find the error and try to resolve that error using the technique mentioned above.

Conclusion

Whenever you get error typeerror: int object is not iterable then you have to check throughout the program and try to find whether you are trying to use non-iterable as an iterable. The most common error I have already shown in the above example and I also gave the solution of those problems.

That’s all for this article.

Thank you.

The post Solve TypeError: ‘int’ object is not iterable in Python appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/FBNhZJxnX

Comments

Popular posts from this blog

Difference between Web Designer and Web Developer Neeraj Mishra The Crazy Programmer

Have you ever wondered about the distinctions between web developers’ and web designers’ duties and obligations? You’re not alone! Many people have trouble distinguishing between these two. Although they collaborate to publish new websites on the internet, web developers and web designers play very different roles. To put these job possibilities into perspective, consider the construction of a house. To create a vision for the house, including the visual components, the space planning and layout, the materials, and the overall appearance and sense of the space, you need an architect. That said, to translate an idea into a building, you need construction professionals to take those architectural drawings and put them into practice. Image Source In a similar vein, web development and design work together to create websites. Let’s examine the major responsibilities and distinctions between web developers and web designers. Let’s get going, shall we? What Does a Web Designer Do?

A guide to data integration tools

CData Software is a leader in data access and connectivity solutions. It specializes in the development of data drivers and data access technologies for real-time access to online or on-premise applications, databases and web APIs. The company is focused on bringing data connectivity capabilities natively into tools organizations already use. It also features ETL/ELT solutions, enterprise connectors, and data visualization. Matillion ’s data transformation software empowers customers to extract data from a wide number of sources, load it into their chosen cloud data warehouse (CDW) and transform that data from its siloed source state, into analytics-ready insights – prepared for advanced analytics, machine learning, and artificial intelligence use cases. Only Matillion is purpose-built for Snowflake, Amazon Redshift, Google BigQuery, and Microsoft Azure, enabling businesses to achieve new levels of simplicity, speed, scale, and savings. Trusted by companies of all sizes to meet

2022: The year of hybrid work

Remote work was once considered a luxury to many, but in 2020, it became a necessity for a large portion of the workforce, as the scary and unknown COVID-19 virus sickened and even took the lives of so many people around the world.  Some workers were able to thrive in a remote setting, while others felt isolated and struggled to keep up a balance between their work and home lives. Last year saw the availability of life-saving vaccines, so companies were able to start having the conversation about what to do next. Should they keep everyone remote? Should they go back to working in the office full time? Or should they do something in between? Enter hybrid work, which offers a mix of the two. A Fall 2021 study conducted by Google revealed that over 75% of survey respondents expect hybrid work to become a standard practice within their organization within the next three years.  Thus, two years after the world abruptly shifted to widespread adoption of remote work, we are declaring 20