TypeError: ‘list’ object is not an iterator

We have covered off many TypeErrors on this website, here we will go through which using a list with and it is not an iterator gives you errors.

In order to understand this error better, we need to first understand what is an iterator in Python?

An iterator is a Python object that has the following characteristics:

  • You can count the no of values that are contained within it.
  • It also can be iterated through, so you need to apply an iteration method to it.

How does this error occur?

Normally this error occurs when you try to iterate over a list, but you have not made the list iterable.

There are two things required to make this happen:

(A) The iter() returns an iterator object

(B) The next() method moves to the next value.

Without both the code will fail and the error you are about will occur!

In the below code we have a list:

a = ['q', 'w', 'e', 'r', 't', 'y']

with the following:

b = next(a)
b = next(a)
b = next(a)
b = next(a)
b = next(a)
b = next(a)

As can be seen in the above code we have one component for the iteration , we expect two as per the above.

As a result we get the error:

Traceback (most recent call last):
  File "list_object_is_not_an_iterator.py", line 13, in <module>
    b = next(a)
TypeError: 'list' object is not an iterator

In order to fix this ,all we need to do is apply the iterator to the list as follows:

a = iter(['q', 'w', 'e', 'r', 't', 'y']) ====> We added in the iter() here, enclosing the list within it

b = next(a)
b = next(a)
b = next(a)
b = next(a)
b = next(a)
b = next(a)
#b = next(a)


print(b)

Giving output:
y

As a result of this, we now have the two required methods that will not give this error.

What is going on within the iterator?

In the above code we have asked to print b. What the iterator is doing is going to the first value of b, in this case q and print.

But because we have a variable b on multiple lines, with the method “next()” in it, the logic is moving through each value of the list till it gets to the end.

What can be done though is , reduce the length of the returned b variables to print as follows:

a = iter(['q', 'w', 'e', 'r', 't', 'y'])
b = next(a)
print(b)
returns:
q

BUT
a = iter(['q', 'w', 'e', 'r', 't', 'y'])
b = next(a)
b = next(a)
print(b)
returns:
w

As can be seen it returns the next value in the list. You can keep adding the b variables.

What happens when you get to the end of the list?

So now we have the below, and we are returning the last value:

a = iter(['q', 'w', 'e', 'r', 't', 'y'])
b = next(a)
b = next(a)
b = next(a)
b = next(a)
b = next(a)
b = next(a)

Returns:
y

The reason for this is that we have the required no of variables with the next method, which equals the length of the list.

If we add in one more b variable:

a = iter(['q', 'w', 'e', 'r', 't', 'y'])
b = next(a)
b = next(a)
b = next(a)
b = next(a)
b = next(a)
b = next(a)
b = next(a) ===> Additional b variable

Returns: 
Traceback (most recent call last):
  File "list_object_is_not_an_iterator.py", line 19, in <module>
    b = next(a)
StopIteration

The purpose of StopIteration is to not allow a continuous loop and recognise that the end of the list has been reached.

Implementing Iterators

Iterators could be used in the following circumstances:

(A) You have a defined list of object values to work with.

(B) If sequence is important an iterator will help to process values in the order they appear in a list.

TypeError: ‘float’ object is not callable

So you have been presented with the TypeError: ‘float’ object is not callable in Python, but unsure how to fix? Well read on so we can get you a solution.

First things an overview of a Float

A float is any number that can contain a decimal place separating an integer from the fractions to the right of the decimal point.

As an example, in the below code, we have the exact same number. But when a computer comes to read it, it treats them differently, due to the fact that b has a decimal point and a fraction to the right of it.

a = 1
b = 1.0

print (type(a))
print (type(b))

Output:
<class 'int'>
<class 'float'>

So how in a piece of code would this error occur?

In the below code, the error occurs. The reason behind this is that float is an actual function that changes a value to a float data type.

As a result, you cannot assign a variable name as “float” and then call it separately in its code. Python specifically does not allow a programmer to use a function as a variable name.

a= float(10)
b= float(11)
c= float(12)
float = a

d = float(a/b*c)
print(d)

Output:
d = float(a/b*c)
TypeError: 'float' object is not callable

So how is this fixed?

In order to fix this, we rename the variable “float” to something else, and make sure that the new name is not another function name!

As can be seen when we do this, the below output runs as expected with no errors:

a= float(10)
b= float(11)
c= float(12)
float_value = a   ===> This line was corrected from above from "float" to "float_value"

d = float(a/b*c)
print(d)

Output: 
10.909090909090908

In summary the crux of this problem is that when creating a variable, it cannot be a function name.

You can see similar posts here on TypeErrors.

Have you seen these posts?

TypeError: ‘float’ object is not callable

TypeError: ‘int’ object is not callable

TypeError: ‘int’ object is not callable

Estimated reading time: 1 minute

We have posted several python solutions to TypeErrors here on the website. Here is another one we hope you will find useful in solving a programming issue you may have.

So what does the error mean?

In the below code, we have four variables that have been assigned an integer.

a= 10
b= 11
c= 12
int= 13

d = int(a/b*c)
print(d)

As can be seen we also have a variable d that is assigned to a function int , that is using the variables a,b,c.

As int is a function it cannot be assigned as a variable, and for this reason the below error will appear:

d = int(a/b*c)
TypeError: 'int' object is not callable

So how can this be fixed?

The solution to this is quite straight forward, it is important not to assign a function as a variable. The fix you would apply is as follows:

Incorrect code:

a= 10
b= 11
c= 12
int = 13  ===> change this line to fix the error

d = float(a/b*c)
print(d)

Corrected code:
a= 10
b= 11
c= 12
int_value = 13  ===> corrected line of code
d = float(a/b*c)
print(d)

Giving you the result:
10

As can also be seen with TypeError: ‘str’ object is not callable assign variables to functions should be avoided at all cost.

TypeError: ‘str’ object is not callable

Estimated reading time: 2 minutes

This is a common TypeError that you will come across in Python, it is actually easy to diagnose how it occurred.

To start off we need to understand “str” is a function in python, and it converts any value into a string.

As a result , because it is a function your ability to call it has limitations.

So in essence it has parenthesis () beside it, and allows parameters to be passed to it.

So lets first look at how the string function works:

x = str("10")
y = 10

print(type(x))
print(type(y))
print(x)
print(y)

With output:
<class 'str'>
<class 'int'>
10
10

As you will see the above the value 10, on its own is an integer, but when you call the string function, it now becomes a string.

For this reason this , calling a string function , completes a conversion to string of ten, but what if the variable is called str?

Lets take an example below from an input:

str = input("what year where you born?")
print(str(str))

Output:

what year where you born?2021
Traceback (most recent call last):
  File "str obj is not callable.py", line 2, in <module>
    print(str(str))
TypeError: 'str' object is not callable

Process finished with exit code 1

The reason for this error above , is that we have named the variable “str”.

As can be seen the programme is trying to use the first str in the print statement as a function.

As we know by now string variables are not callable.

Accordingly the function str() which the programme is trying to run, fails with the TypeError identified.

For this reason to fix this problem we would change the variable called str to “year”, the error then disappears.

The updated code will work as when calling str(), it is not conflicted with a variable name.

year = input("what year where you born?")
print(str(year))

Output:
"str obj is not callable.py"
what year where you born?2021
2021

Process finished with exit code 0

So to summarise:

  • Strings are not callable
  • Don’t name a variable as str, or any function name, these are reserved words by the system.
  • Functions are callable, strings are not.

TypeError object of type ‘int’ has no len()

I have seen this data type error come up numerous times while working on my data analytics projects, and recently decided to investigate further. On initial inspection, it can seem a bit of a funny one, but in actual fact, it is quite straight forward.

Lets break it down and see what is going on

So in the below code, there are a number of things:

On line 1 we have a variable that is an integer. If we think about this logically, something that is a single numeric number cannot have a length.

An integer by design is purely to count up a number of apples or no of people, it cannot be viewed as having a length as it is descriptive of the number of occurrences of an object.

data = 100
print(type(data))
print(len(data))

Output Error:
<class 'int'>
Traceback (most recent call last):
  File "object of type int.py", line 3, in <module>
    print(len(data))
TypeError: object of type 'int' has no len()

So for it to in anyway allow a length to be calculated, the object needs to be one of the following data types:

  • List
  • String
  • Tuple
  • Dictionary

Opposite to an integer, these are datatypes that have values that would be more appropriate to having values that a length can be calculated on.

data = "100"
print(type(data))
print("Length of string is: ", len(data))

data = [100,200,300]
print(type(data))
print("Length of list is: ", len(data))

data = (100,200,300)
print(type(data))
print("Length of tuple is: ", len(data))

data = {"Age": 1, "Name": 2}
print(type(data))
print("Length of dictionary is: ", len(data))

And the output is:
<class 'str'>
Length of string is:  3
<class 'list'>
Length of list is:  3
<class 'tuple'>
Length of tuple is:  3
<class 'dict'>
Length of dictionary is:  2

In summary, to understand this error and fix it:

An integer describes the number of things that exist for an object, they are actually not the actual object in existence.

Anything that can have a length method applied to it actually exists and can be counted. In the above four examples, they are actually values that you could describe as existing as you can count each one of them.

The explanation here hopefully clears up the matter, if you have any questions leave a comment and I will answer for you!

raise an exception in python

Estimated reading time: 5 minutes

In a computer programme, there is a lot of different moving parts, that the programmer has created themselves.

And depending on the sophistication of the code written exceptions can occur, usually no one has an understanding of what they mean!

So we have established problems can occur, what next?

As part of the process of building out the logic , knowledge will lie with the computer programmer.

In this case the errors that they know about and programme for, may not always be understood by everyone.

If the computer programme does not explain them correctly, frequently it can lead to long hours trying to figure out the problem.

This is usually because the error message they code to explain the problem, may not always be designed with ease of understandability.

It must be remembered:

  • Not all errors may be known when the programme was developed.
  • Some error messages can be generated automatically, not on the request of the programmer.

Step into the frame, the ability to create your own error messages with understandable explanations.

Good programmers have a lot of traits that makes what they develop so powerful.

Surprisingly it is the simple things can be missed, but based on time and budget, generic error messages may be needed, certainly not ideal though.

With that in mind lets look at the following code:

def checkvalue():
    try:
        integervalues = input("Type something to test this out: ")
        if integervalue != "55" and integervalue.isdecimal():
            raise ValueError
        elif integervalue.isalpha():
            raise TypeError
        else:
            print("55 entered correctly")
    except ValueError:
        raise ValueError("Integervalue needs to be fifty five")
    except TypeError:
        raise TypeError("Number needs to be entered")
    finally:
        print("All checks completed")


checkvalue()
It returns:
NameError: name 'integervalue' is not defined

The problem is that the variable used has a misspelling.

Luckily we can easily see that the variable “integervalue” is misspelt with an extra “s”, however removing that will fix the issue.

In the light of that say we took the above code, without the try and except:

from distlib.compat import raw_input
def checkvalue():
    integervalue =raw_input("Type something to test this out: ")

    if integervalue == int(55):
        print("success")
    else:
        print("integervalue needs to be a fifty five")


checkvalue()
It returns:
Type something to test this out: aa
integervalue needs to be a fifty five

In essence, both do the same thing, above all the first piece of code allows for better customization.

This allows us to test for specific types of errors, resulting in more specific error trapping like:

  • Value Error
  • Type Error

The above two are just examples you can use for built in exceptions coded to trap errors.

But what if we want to create our own exception list?

The simple way around this is to build your own class that has the errors you need to capture.

Then you reference that class in the try/except and bingo, there you have it.

In order to achieve this, the first step is to build classes with the errors you want to catch:

class ValueTooSmall(Exception):
    """Raised when the input value is too small"""
    pass
class ValueLength(Exception):
    """Raised when the value entered is empty"""
    pass
class ValueAlphabetic(Exception):
    """Raised when the value is alphabetic"""
    pass

Then create a function that will hold all the try except logic to check for the errors

try:
        integervalue = input("Type something to test this out: ") # Creates a string here
        if len(integervalue) == 0:
            raise ValueLength
        elif integervalue.isalpha():
            raise ValueAlphabetic
        elif int(integervalue) != 55 and int(integervalue) < 10: # converting to integer to allow comparison
            raise ValueTooSmall
        elif int(integervalue) != 55 and int(integervalue) > 10: # converting to integer to allow comparison
            raise ValueError
        else:
            print("55 entered correctly")
    except ValueError:
        raise ValueError("Integervalue needs to be fifty five")
    except TypeError:
        raise TypeError("Number needs to be entered")
    except ValueTooSmall:
        raise ValueTooSmall("Number needs to be greater than 10")
    except ValueLength:
        raise ValueLength("Number needs to be entered, can't be empty")
    except ValueAlphabetic:
        raise ValueAlphabetic("You cannot enter an alphabetic value")
    finally:

Putting it all together

class ValueTooSmall(Exception):
    """Raised when the input value is too small"""
    pass
class ValueLength(Exception):
    """Raised when the value entered is empty"""
    pass
class ValueAlphabetic(Exception):
    """Raised when the value is alphabetic"""
    pass

def checkvalue():
    try:
        integervalue = input("Type something to test this out: ") # Creates a string here
        if len(integervalue) == 0:
            raise ValueLength
        elif integervalue.isalpha():
            raise ValueAlphabetic
        elif int(integervalue) != 55 and int(integervalue) < 10: # converting to integer to allow comparison
            raise ValueTooSmall
        elif int(integervalue) != 55 and int(integervalue) > 10: # converting to integer to allow comparison
            raise ValueError
        else:
            print("55 entered correctly")
    except ValueError:
        raise ValueError("Integervalue needs to be fifty five")
    except TypeError:
        raise TypeError("Number needs to be entered")
    except ValueTooSmall:
        raise ValueTooSmall("Number needs to be greater than 10")
    except ValueLength:
        raise ValueLength("Number needs to be entered, can't be empty")
    except ValueAlphabetic:
        raise ValueAlphabetic("You cannot enter an alphabetic value")
    finally:
        print("All checks completed")


checkvalue()

You will notice that the Classes we created are referenced within the code to call the exact exception we are looking to capture.

For this reason what are the benefits of approaching it this way:

  • You can capture exceptions tailored to the code you are writing.
  • Controls can easily be created and implemented so that specific errors with your data can be flagged straight away.
  • If you are going to be looking to catch the same exceptions in numerous places, this methodology will help to implement a better structure to handle those.
  • You can start to build a centralised repository of centralized exceptions and how to handle them.
  • All contributors to your project know how to raise an exception in python , you do not get multiple different v.

On our YouTube channel you can subscribe to find out more information about exceptions, and lots of tips and tricks for better Data Analytics.