Python detect and prevent TypeError: sequence item 0 and join iterable

Errors in Python are explicit and provide good amount of information. For example errors:

TypeError: sequence item 0: expected str instance, int found

and

TypeError: can only join an iterable

Video tutorial can be found here: Python 3 detect and prevent TypeError-s

It's TypeError and it's describing that string is expected but is found integer. Still many beginners in programming and python suffer when the see errors like this. Below you can example code which cause the error:

mylist = [1, 2, 3, 4]
print(', '.join(mylist))

the result of this execution is:

TypeError: sequence item 0: expected str instance, int found

Which means that method join expect list of string and you give list of integers. One way to solve is to convert elements of your list to strings:

mylist = [1, 2, 3, 4]
print(list(map(str, mylist)))

result:

['1', '2', '3', '4']

then you can apply functions like join:

mylist = [1, 2, 3, 4]
print('; '.join(list(map(str, mylist))))

to get:

1; 2; 3; 4

A better way is to iterate all the list elements and convert them to strings like:

mylist = [1, 2, 3, 4]
print('; '.join(map(str, mylist)))

or

mylist = [1, 2, 3, 4]
print('; '.join(str(x) for x in mylist))

result of which is:

1; 2; 3; 4

Another common error for beginners is:

TypeError: can only join an iterable

This error is also obvious. Below you can find example and explanation of it:

mylist = 2
print(', '.join(mylist))

which results into:

TypeError: can only join an iterable

As you guess the problem is that method join expect a list or iterable but receive a type which is not. Most probably this error is related to semantic error in your code and it's better to find why do you have situation like this. Of course a quick workaround would be:

mylist = list(str(2))
print(', '.join(mylist))

But it is much better to catch or avoid errors like this one. There are several ways of doing this:

Use try except block to ensure that all errors are catch and your code is safe:

import collections
mylist = 2
if isinstance(mylist, collections.Iterable):
    print(', '.join(mylist))

or check the object type and then decide how to treat it:

try:
    iterator = iter(mylist)
except TypeError:
    print('not iterable')
else:
    print(', '.join(mylist))

Both ways ensure that your code is secure against errors like this last two.

Related Article