Sequence item 0: expected str instance, list found (Python)

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Ken Cheung

Sequence item 0: expected str instance, list found (Python) #

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.

typeerror sequence item 0 expected str instance list found

Here is an example of how the error occurs.

main.py
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().

main.py
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.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

If your nested lists might contain non-string values, you'll have to convert each value to a string.

main.py
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.

main.py
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.

Note that the method raises a 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().

main.py
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.

main.py
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.

main.py
my_list = ['a', 'b', 'c'] my_str = ''.join(my_list) print(my_str) # 👉️ "abc"
Use the search field on my Home Page to filter through my more than 1,000 articles.