Typeerror: can only join an iterable
Are you encountering Typeerror: can only join an iterable ?
Well, joining strings can be a powerful tool in Python, allowing you to easily concatenate multiple strings into one. However, it’s important to remember that not all objects are iterable.
Apparently, this could be the reason why the error is triggered.
In this guide, we will provide you with some practical solutions and examples to solve this error and help you write error-free Python code.
Please enable JavaScript
So, let’s dive in and fix that error!
What is Typeerror: can only join an iterable?
The Python “TypeError: can only join an iterable” is an error typically occurs when we try to concatenate a string with a non-iterable object, such as an integer or a float.
Further, the join() method in python is used to join the elements of an iterable object, such as a list or a tuple, into a string.
However, this method can only be used with iterable objects, and not with non-iterable objects.
For instance, we have a list of strings and we want to join them into a single string separated by a comma.
We could use the join() method like this:
This would output the following.
blue, red, orange
However, if we try to use the join() method with a non-iterable object, such as an integer or a float, we would get the “TypeError: can only join an iterable” error message.
In the next section, you will see how this error occurs.
Example Scenario of Typeerror: can only join an iterable
Here is how this error occurs:
In this example, the variable num is an integer, which is a non-iterable object. When we try to use the join() method on num, we get a “TypeError: can only join an iterable” error.
Solutions for Typeerror: can only join an iterable
Certainly! Here are some solutions for the “TypeError: can only join an iterable” error
1. Convert the non-iterable object to an iterable object before using join()
If you are trying to join a non-iterable object, such as an integer or a float, you need to convert it to an iterable object before using the join() method.
One way to do this is to convert the object to a string using the str() function, and then split the string into individual characters or digits using the list() function.
For example:
Output:
1-0-2-0-3-0
2. Use a different method to concatenate the string and the non-iterable object.
If you are trying to concatenate a string with a non-iterable object, such as an integer or a float, you can use a different method to do so, such as string formatting or concatenation.
For example:
Output:
The number is 123
3. Check the type of the object before using join()
Before using the join() method, you can check the type of the object to make sure it is iterable.
If it is not iterable, you can use one of the other solutions listed above to convert it to an iterable object or concatenate it with a string in a different way.
For example:
Output:
42
Anyway, we also have a solution for Typeerror series objects are mutable thus they cannot be hashed errors, you might encounter.
Factors caused Python typeerror can only join an iterable
- Attempting to use join() on a non-iterable object.
- Using the wrong syntax when calling join().
- Trying to join an object that is not a string.
- Passing the wrong type of iterable to join().
- Using a non-string separator.
Conclusion
To conclude, Typeerror: can only join an iterable will occur when we try to concatenate a string with a non-iterable object, such as an integer or a float.
To fix this error, we need to convert the non-iterable object to an iterable object before using join(), or use a different method to concatenate the string and the non-iterable object
We hope this guide helped you fix your error and get back on your coding.
Python – “Can only join an iterable” python error
I've already looked at this post about iterable python errors:
But that was about the error "cannot assign an iterable". My question is why is python telling me:
I don't know what I am doing wrong! I was following this thread:
and specifically this answer:
and adapter the code to make it have an input. But when I ran it, it said the error above. I am a complete novice so could you please tell me what the error message means and how to fix it.
The program should take an input like apples and pears and then produce an output pears and apples.
Help would be appreciated!
Best Solution
splitlist1.reverse() , like many list methods, acts in-place, and therefore returns None . So tobereversedlist1 is therefore None, hence the error.
You should pass splitlist1 directly:
Related Solutions
Python – What are metaclasses in Python
Classes as objects
Before understanding metaclasses, you need to master classes in Python. And Python has a very peculiar idea of what classes are, borrowed from the Smalltalk language.
In most languages, classes are just pieces of code that describe how to produce an object. That's kinda true in Python too:
But classes are more than that in Python. Classes are objects too.
As soon as you use the keyword class , Python executes it and creates an object. The instruction
creates in memory an object with the name ObjectCreator .
This object (the class) is itself capable of creating objects (the instances), and this is why it's a class.
But still, it's an object, and therefore:
- you can assign it to a variable
- you can copy it
- you can add attributes to it
- you can pass it as a function parameter
Creating classes dynamically
Since classes are objects, you can create them on the fly, like any object.
First, you can create a class in a function using class :
But it's not so dynamic, since you still have to write the whole class yourself.
Since classes are objects, they must be generated by something.
When you use the class keyword, Python creates this object automatically. But as with most things in Python, it gives you a way to do it manually.
Remember the function type ? The good old function that lets you know what type an object is:
Well, type has a completely different ability, it can also create classes on the fly. type can take the description of a class as parameters, and return a class.
(I know, it's silly that the same function can have two completely different uses according to the parameters you pass to it. It's an issue due to backward compatibility in Python)
type works this way:
- name : name of the class
- bases : tuple of the parent class (for inheritance, can be empty)
- attrs : dictionary containing attributes names and values
can be created manually this way:
You'll notice that we use MyShinyClass as the name of the class and as the variable to hold the class reference. They can be different, but there is no reason to complicate things.
type accepts a dictionary to define the attributes of the class. So:
Can be translated to:
And used as a normal class:
And of course, you can inherit from it, so:
Eventually, you'll want to add methods to your class. Just define a function with the proper signature and assign it as an attribute.
And you can add even more methods after you dynamically create the class, just like adding methods to a normally created class object.
You see where we are going: in Python, classes are objects, and you can create a class on the fly, dynamically.
This is what Python does when you use the keyword class , and it does so by using a metaclass.
What are metaclasses (finally)
Metaclasses are the 'stuff' that creates classes.
You define classes in order to create objects, right?
But we learned that Python classes are objects.
Well, metaclasses are what create these objects. They are the classes' classes, you can picture them this way:
You've seen that type lets you do something like this:
It's because the function type is in fact a metaclass. type is the metaclass Python uses to create all classes behind the scenes.
Now you wonder "why the heck is it written in lowercase, and not Type ?"
Well, I guess it's a matter of consistency with str , the class that creates strings objects, and int the class that creates integer objects. type is just the class that creates class objects.
You see that by checking the __class__ attribute.
Everything, and I mean everything, is an object in Python. That includes integers, strings, functions and classes. All of them are objects. And all of them have been created from a class:
Now, what is the __class__ of any __class__ ?
So, a metaclass is just the stuff that creates class objects.
You can call it a 'class factory' if you wish.
type is the built-in metaclass Python uses, but of course, you can create your own metaclass.
The __metaclass__ attribute
In Python 2, you can add a __metaclass__ attribute when you write a class (see next section for the Python 3 syntax):
If you do so, Python will use the metaclass to create the class Foo .
Careful, it's tricky.
You write class Foo(object) first, but the class object Foo is not created in memory yet.
Python will look for __metaclass__ in the class definition. If it finds it, it will use it to create the object class Foo . If it doesn't, it will use type to create the class.
Read that several times.
Python does the following:
Is there a __metaclass__ attribute in Foo ?
If yes, create in-memory a class object (I said a class object, stay with me here), with the name Foo by using what is in __metaclass__ .
If Python can't find __metaclass__ , it will look for a __metaclass__ at the MODULE level, and try to do the same (but only for classes that don't inherit anything, basically old-style classes).
Then if it can't find any __metaclass__ at all, it will use the Bar 's (the first parent) own metaclass (which might be the default type ) to create the class object.
Be careful here that the __metaclass__ attribute will not be inherited, the metaclass of the parent ( Bar.__class__ ) will be. If Bar used a __metaclass__ attribute that created Bar with type() (and not type.__new__() ), the subclasses will not inherit that behavior.
Now the big question is, what can you put in __metaclass__ ?
The answer is something that can create a class.
And what can create a class? type , or anything that subclasses or uses it.
Metaclasses in Python 3
The syntax to set the metaclass has been changed in Python 3:
i.e. the __metaclass__ attribute is no longer used, in favor of a keyword argument in the list of base classes.
The behavior of metaclasses however stays largely the same.
One thing added to metaclasses in Python 3 is that you can also pass attributes as keyword-arguments into a metaclass, like so:
Read the section below for how Python handles this.
Custom metaclasses
The main purpose of a metaclass is to change the class automatically, when it's created.
You usually do this for APIs, where you want to create classes matching the current context.
Imagine a stupid example, where you decide that all classes in your module should have their attributes written in uppercase. There are several ways to do this, but one way is to set __metaclass__ at the module level.
This way, all classes of this module will be created using this metaclass, and we just have to tell the metaclass to turn all attributes to uppercase.
Luckily, __metaclass__ can actually be any callable, it doesn't need to be a formal class (I know, something with 'class' in its name doesn't need to be a class, go figure. but it's helpful).
So we will start with a simple example, by using a function.
Now, let's do exactly the same, but using a real class for a metaclass:
Let's rewrite the above, but with shorter and more realistic variable names now that we know what they mean:
You may have noticed the extra argument cls . There is nothing special about it: __new__ always receives the class it's defined in, as the first parameter. Just like you have self for ordinary methods which receive the instance as the first parameter, or the defining class for class methods.
But this is not proper OOP. We are calling type directly and we aren't overriding or calling the parent's __new__ . Let's do that instead:
We can make it even cleaner by using super , which will ease inheritance (because yes, you can have metaclasses, inheriting from metaclasses, inheriting from type):
Oh, and in Python 3 if you do this call with keyword arguments, like this:
It translates to this in the metaclass to use it:
That's it. There is really nothing more about metaclasses.
The reason behind the complexity of the code using metaclasses is not because of metaclasses, it's because you usually use metaclasses to do twisted stuff relying on introspection, manipulating inheritance, vars such as __dict__ , etc.
Indeed, metaclasses are especially useful to do black magic, and therefore complicated stuff. But by themselves, they are simple:
- intercept a class creation
- modify the class
- return the modified class
Why would you use metaclasses classes instead of functions?
Since __metaclass__ can accept any callable, why would you use a class since it's obviously more complicated?
There are several reasons to do so:
- The intention is clear. When you read UpperAttrMetaclass(type) , you know what's going to follow
- You can use OOP. Metaclass can inherit from metaclass, override parent methods. Metaclasses can even use metaclasses.
- Subclasses of a class will be instances of its metaclass if you specified a metaclass-class, but not with a metaclass-function.
- You can structure your code better. You never use metaclasses for something as trivial as the above example. It's usually for something complicated. Having the ability to make several methods and group them in one class is very useful to make the code easier to read.
- You can hook on __new__ , __init__ and __call__ . Which will allow you to do different stuff, Even if usually you can do it all in __new__ , some people are just more comfortable using __init__ .
- These are called metaclasses, damn it! It must mean something!
Why would you use metaclasses?
Now the big question. Why would you use some obscure error-prone feature?
Well, usually you don't:
Metaclasses are deeper magic that 99% of users should never worry about it. If you wonder whether you need them, you don't (the people who actually need them to know with certainty that they need them and don't need an explanation about why).
Python Guru Tim Peters
The main use case for a metaclass is creating an API. A typical example of this is the Django ORM. It allows you to define something like this:
But if you do this:
It won't return an IntegerField object. It will return an int , and can even take it directly from the database.
This is possible because models.Model defines __metaclass__ and it uses some magic that will turn the Person you just defined with simple statements into a complex hook to a database field.
Django makes something complex look simple by exposing a simple API and using metaclasses, recreating code from this API to do the real job behind the scenes.
The last word
First, you know that classes are objects that can create instances.
Well, in fact, classes are themselves instances. Of metaclasses.
Everything is an object in Python, and they are all either instance of classes or instances of metaclasses.
Except for type .
type is actually its own metaclass. This is not something you could reproduce in pure Python, and is done by cheating a little bit at the implementation level.
Secondly, metaclasses are complicated. You may not want to use them for very simple class alterations. You can change classes by using two different techniques:
99% of the time you need class alteration, you are better off using these.
But 98% of the time, you don't need class alteration at all.
Python – How to safely create a nested directory in Python
For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:
Try os.path.exists , and consider os.makedirs for the creation.
As noted in comments and elsewhere, there's a race condition – if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError . Unfortunately, blanket-catching OSError and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.
One option would be to trap the OSError and examine the embedded error code (see Is there a cross-platform way of getting information from Python’s OSError):
Alternatively, there could be a second os.path.exists , but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.
Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.
Modern versions of Python improve this code quite a bit, both by exposing FileExistsError (in 3.3+).
"Can only join an iterable" python error
splitlist1.reverse() , like many list methods, acts in-place, and therefore returns None . So tobereversedlist1 is therefore None, hence the error.
You should pass splitlist1 directly:
Solution 2
string join must satisfy the connection object to be iterated(list, tuple)
splitlist1.reverse() returns None, None object not support iteration.
Derek
Updated on April 11, 2020
Comments
I’ve already looked at this post about iterable python errors:
But that was about the error «cannot assign an iterable». My question is why is python telling me:
I don’t know what I am doing wrong! I was following this thread:
and specifically this answer:
and adapter the code to make it have an input. But when I ran it, it said the error above. I am a complete novice so could you please tell me what the error message means and how to fix it.
The program should take an input like apples and pears and then produce an output pears and apples.
How To Solve “TypeError: Can Only Join An Iterable” In Python
Python has a .join() method that helps you combine all elements in a list into a string . However, when using this method, many developers get the error message, which is TypeError: Can only join an iterable . In this article, we will find out the cause of this error and the solution to it!
Cause Of “TypeError: can only join an iterable” in Python
Here is a sample: you have a list of unsorted fruit names like so:
lstFruit = [«Apple», «Orange», «Banana», «Durian»]
You want to sort the list in alphabetical order and then combine all these fruits into a string using the method .join() .
The sample is below:
Unfortunately, an error message shows up:
The cause for this issue is easy to explain. The .join() method only receives an iterable as its parameter. The error appears when you try to add a non-iterable to the .join() .
The problem is not due to the .join() method but how you sort the list. The .sort() function in Python works in place and returns a None value. In other words, .sort() does not return a list but only a non-iterable .
Table of Contents
How to solve TypeError: can only join an iterable in Python
Step 1: Make the list an iterable
As mentioned, the .sort() method does not return an iterable . Therefore, when you use the command:
The list will get the None value.
You can see the sample code below:
The output will be:
The .sort() sorts the list in place. Therefore, you should not assign the result of the .sort() to a variable. You should just call the method alone. Then the list will be sorted without receiving the None value. The sample is below:
The output will be:
Besides the .sort() method, many other methods, such as .remove() and .reverse() , also return a None value. Therefore, you can only put the command alone to keep the list as an iterable .
Step 2: Transform the list into a string using the .join() method
Since the list is iterable , you can use the method .join() to transform it into a string without receiving any issues.
The list does not have a None value now. Therefore, you can use it as the parameter for the .join() method.
The sample code is below:
The output will be:
Summary
The TypeError: can only join an iterable in Python occurs every time you try to put a non-iterable as a parameter for the .join() method. You need to keep in mind that several methods that work with a list , including .remove() , . sort() , and .reverse() , will only return a None value, which is not iterable . Thus, the solution is to make a list as an iterable before using the .join() !

I am William Nguyen and currently work as a software developer. I am highly interested in programming, especially in Python, C++, Html, Css, and Javascript. I’ve worked on numerous software development projects throughout the years. I am eager to share my knowledge with others that enjoy programming!