Python TypeError: sequence item N: expected string, list found
A quick and easy way of fixing this error is by applying the
map()
function to your
join()
argument:
In this example,
map()
is transforming every value in
nested_list()
to string-type, allowing
join()
to concatenate all of the list values. This process is explained more in-depth in the
map()
section of this article.
Why does this occur?
This error occurs because the list passed as an argument to the
join()
method contains a nested list.
join()
can only
concatenate string-type objects
, so Python throws an error if we use
join()
with anything that isn't a string.
As a result, using
join()
with a list containing integers, floats, or tuples results in a similar error, with
list found
being replaced by
int found
,
float found
, or
tuple found
.
Today we'll take a look at an example case of where we might see this error, along with some solutions that demonstrate how we can solve it.
Solution 1: for loop, generator, or list comprehension
As mentioned in the intro, this error occurs when we apply the
join()
method while using a list that contains a nested list.
Let's say you're analyzing some vehicle data. You've got a JSON file that contains data for different vehicles in the following format:
We want to view all of the values for a given vehicle. We could try to do this using our Jaguar example with the following:
As the error shows, sequence item 3 (the
available_colors
row) is a list, which means
join()
won't work here. We can get around this by using a
for
loop, generator, or list comprehension. Here's an example using a generator:
The generator iterates through each list item and converts the value to a string-type object, allowing
join()
to work.
Solution 2: map()
We can also troubleshoot this error using the
map()
function, as shown in the intro. We can apply
map()
to our vehicle example as follows:
map()
works by looping through a list given as the second argument. In our case, this is
vehicle_info
. It then applies whichever
transformation function
we provide as the first argument. Using
str()
as our transformation function converts everything in the list to a string, including our list of colors.
On the surface, a generator essentially goes through the same process as the
map()
function does, iterating through each item in the list and then applying the
str()
function. However, Python works its way through the statements very differently, with
map()
executing much faster than a generator. See below for a speed comparison of our two examples, which shows that our script runs faster while using
map()
: