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: cannot unpack non-iterable int object

Often when working on a data analytics project it requires you to split data out into its constituent parts.

There are a number of reasons for this, it can be confusing when you get errors as with the title of this post.

Before we explain this error and what it means, lets us first explain unpacking

Unpacking basically means splitting something up into a number of its parts that make it up.

To demonstrate if you take a,b,c = 123, and look to unpack it, it throws out the error, but why?

Well pure and simple, we have three values on the left “a,b,c”, looking for three values on the right.

a,b,c = 123
print(a)

Output:
 a,b,c = 123
TypeError: cannot unpack non-iterable int object

If you would like to fix this problem change the right hand side to have three values.

a,b,c = 1,2,3
print(a)
print(b)
print(c)
print(a,b,c)

Output:
1
2
3
1 2 3

Process finished with exit code 0

In essence, what is going on is that an evaluation checking that both sides have the same amount of values.

It is important to remember, the code above we used to show the error is an integer, which cannot be unpacked.

So if you take 123 for an example, which we used here it cannot be split into say 100 and 10 and 13.

In this case, even though when they are added up to 123, integers cannot be unpacked.

For this reason in the code for our solution, the difference is that the values used are tuples as follows:

a,b,c = 1,2,3
print(a)
print(b)
print(c)
print(a,b,c)
print(type((a,b,c)))

Or 
a,b,c = (1,2,3)
print(a)
print(b)
print(c)
print(a,b,c)
print(type((a,b,c)))

yield the same result:

1
2
3
1 2 3
<class 'tuple'>

Process finished with exit code 0

So in summary:

When unpacking there are a number of things to remember:

  • Integers on their own cannot be unpacked.
  • You need to make sure that if you have a number of variables, that you have the same number of integers if they the values.
    • This will make it a tuple and unpacking can then happen.

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!

type object is not subscriptable

Estimated reading time: 2 minutes

I was recently working on our last blog post how to reverse a string in python and I came across this error.

The thought passed me what does it mean and how can I fix it?

So what does the error actually mean?

Essentially it means that , you are trying to access a type of an object, that has a property of “type”.

What is property of type? Well it is :

  • int()
  • str()
  • tuple()
  • dict()

The above alllow you to change your data to these data types, so the data contained within them can be further manipulated.

In essence you are trying to use a type in the wrong way and in the wrong place in your code.

By calling it , it will throw this error, and they should be avoided, as a it is a built in function.

Lets take an example of how we can replicate this error and fix it

name1 = "joe"
emptylist =[]
strlength = len(name1)
while strlength > 0:
    emptylist += str[ strlength -1 ]
    strlength = strlength - 1
print(emptylist)

In the above code all appears well, but in line 5 the “str” before the [ is the problem. The code automatically looks to call this function.

The simple answer to fixing this is to rename it to name1 as follows:

name1 = "joe"
emptylist =[]
strlength = len(name1)
while strlength > 0:
    emptylist += name1[ strlength -1 ]
    print(type(emptylist))
    strlength = strlength - 1
print(emptylist)

which gives you the following error free output:

Result with no error: ['e', 'o', 'j']

In summary and what not to do

So it is clear that referencing types as a string variable should be avoided, and keep your code clean from this perspective.

This would also apply to any reserved words in Python as well.

How do I fix TypeError: unhashable type: ‘list’ Error?

Estimated reading time: 3 minutes

When programming in python you will come across this error quite often, in this case is quite easily fixed once understood.

The problem usually arises when you try to loop through a dictionary with key-value pairs. If you are unsure what a dictionary looks like see W3 Schools

Lets examine those loops that don’t throw the error.

Using a list, produces the following output with no error:

list = [['a'],['b'],['c'],['d'],['e'],['f']]

print(type(list))

for i in list:
    print(i)

<class 'list'>
['a']
['b']
['c']
['d']
['e']
['f']

If there is a need for a tuple, then the following outputs with no error:

list = (['a'],['b'],['c'],['d'],['e'],['f'])

print(type(list))

for i in list:
    print(i)

<class 'tuple'>
['a']
['b']
['c']
['d']
['e']
['f']

Using a dictionary, it gives the error you are looking to resolve, but why?

list = {['a'],['b'],['c'],['d'],['e'],['f']}

print(type(list))

for i in list:
    print(i)

list = {['a'],['b'],['c'],['d'],['e'],['f']}
TypeError: unhashable type: 'list'

To understand the error it is important to step back and figure out what is going on in each scenario:

(A) Looping through the list, it looks at the values on their own, thus the loop completes with no problem.

(B) As with lists, Tuples are immutable ( cannot be modified), more importantly, they can be looped through with no error.

In this case the lists have single values, the dictionary above has only one value, it expects two, hence the error.

How do we fix this error going forward?

The simplest way is to loop through a list of single items with the iterable code below:

fixlist = [['a'],['b'],['c'],['d'],['e'],['f'],['f'],['c']]

# Converts fixlist from a list of lists to a flat list, and removes duplicates with set
fixlist  = list(set(list(itertools.chain.from_iterable(fixlist))))

print(fixlist)
Result : ['d', 'f', 'c', 'b', 'a', 'e']

Now your code is only looking to loop through some single values within your list, compared to dictionary key-value pairs.

Approaching solving this problem through an iteration line by line helped to pinpoint the problem.

Consequently the steps I went through to fix the problem involved:

(A) print(type(variable)) – Use this on passing data to see what the data types are, clarifies if this is the problem.

(B) Consequently once the line of code that was throwing the error was found, removing the dictionary fixed the problem.

Or

If a dictionary is required to be looped through, it needs the proper key, value pairs setup.

Conclusion

In conclusion, in order to remove this error it is important to identify the line and or lines, that have a dictionary and covert them to a list

or

if a dictionary is needed ensure that the lists are converted to a dictionary with key, value pairs.

If you would like to see a very good video explanation of this error head over to Brandon Jacobson’s YouTube channel , and make sure to subscribe.

His explantion is below: