Python Join List Example
In this article, we will explain how to use the function Join List in Python through examples.
1. Introduction
Python join()
function means concatenating an iterable of strings with a specified delimiter to form a string
. Sometimes it’s useful when you have to convert an iterable
to a string
.
2. How to Use join list in Python
The syntax of the join
function is str.join(iterable)
where str
is the specified delimiter. Also, TypeError
will be raised if there are any non-string values in iterable
, including bytes
objects.
joinExample.py
tmpList = ["food", "music", "car", "work", "dance"] output = " and ".join(tmpList) print(output)
3. Why join() Function is in String and not in List?
This is a question that many python developers have. The most important point from the discussions on the internet is because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the delimiter must be strings
. That means that is harder to program and optimize the join()
function for all the different iterable objects
in order to work. For that reason is much simpler to be a String
method and not an Iterable
method.
4. Joining List of Multiple data-types Example
Because join() function accepts only iterable with String Elements, in order to join a List of multiple data-types, we must cast its element into a string. Lets see an example.
joinExample.py
multiList = ["food" , 666 , 12.3 , "dance"] output = " and ".join(map(str, multiList)) print(output)
- line 1: We create a list with multiple data-types.
- line 3: We use as before the
join()
function but this time we use themap()
function in order to cast its element into astring
. Themap()
function returns aniterable
that appliesstr
to every item ofmultilist
.
5. Split String Using join() Function Example
We can use the join() function in order to split a string to its of its letters.
joinExample.py
tmpString = "Potato" output = " , ".join(tmpString) print(output)
6. Summary
As we can see from the examples above, the join()
method provides a flexible way to create strings
from iterable
objects.
7. More articles
8. Download Source Code
This was an example of how we can use the join() function in python.
You can download the full source code of this example here: Python Join List Example