Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Ken Cheung
The Python "TypeError: sequence item 0: expected str instance, list found"
occurs when we call the join()
method with an iterable that contains one or
more list objects. To solve the error, use a nested join()
to join the
elements of each list.
Here is an example of how the error occurs.
my_list = [['a', 'b'], ['c', 'd']] # ⛔️ TypeError: sequence item 0: expected str instance, list found result = ''.join(my_list)
The join
method raises a TypeError
if there are any non-string values in the
iterable.
One way to solve the error is to use a generator expression with a nested
join()
.
my_list = [['a', 'b'], ['c', 'd']] result = ''.join(''.join(l) for l in my_list) print(result) # 👉️ "abcd"
We called the join()
method with each nested list and then joined the strings.
If your nested lists might contain non-string values, you'll have to convert each value to a string.
my_list = [[1, 2], ['c', 'd']] result = ''.join(''.join(map(str, l)) for l in my_list) print(result) # 👉️ "12cd"
The map() function takes a function and an iterable as arguments and calls the function on each item of the iterable.
If you want to join the nested lists into a string, you can pass each list to
the str()
class.
my_list = [['a', 'b'], ['c', 'd']] result = ''.join(str(l) for l in my_list) print(result) # 👉️ "['a', 'b']['c', 'd']"
The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.
TypeError
if there are any non-string values in the iterable.If your list contains numbers, or other types, convert all of the values to
string before calling join()
.
my_list = ['a', 'b', 1, 2] all_strings = list(map(str, my_list)) print(all_strings) # 👉️ ['a', 'b', '1', '2'] result = ''.join(all_strings) print(result) # 👉️ "ab12"
The string the method is called on is used as the separator between elements.
my_list = ['a', 'b', 'c'] my_str = '-'.join(my_list) print(my_str) # 👉️ "a-b-c"
If you don't need a separator and just want to join the iterable's elements into
a string, call the join()
method on an empty string.
my_list = ['a', 'b', 'c'] my_str = ''.join(my_list) print(my_str) # 👉️ "abc"