Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Khamkéo Vilaysing
The Python "TypeError: can only concatenate list (not "str") to list" occurs
when we try to concatenate a list and a string. To solve the error, use the
append()
method to add an item to the list, e.g.
my_list.append('my item')
.
Here is an example of how the error occurs.
my_list = ['apple', 'banana'] my_str = 'melon' # ⛔️ TypeError: can only concatenate list (not "str") to list result = my_list + my_str
We tried to use the addition (+) operator to add an item to a list which caused the error.
You can use the append()
method to add an item to a list.
my_list = ['apple', 'banana'] my_str = 'melon' my_list.append(my_str) print(my_list) # 👉️ ['apple', 'banana', 'melon']
The list.append() method adds an item to the end of the list.
The method returns None
as it mutates the original list.
Alternatively, you can wrap the string in a list if you'd prefer to use the addition (+) operator.
my_list = ['apple', 'banana'] my_str = 'melon' result = my_list + [my_str] print(result) # 👉️ ['apple', 'banana', 'melon']
However, using the append()
method is much more common.
Conversely, if you need to remove an item from a list, use the remove()
method.
my_list = ['apple', 'banana'] my_str = 'banana' my_list.remove(my_str) print(my_list) # 👉️ ['apple']
The list.remove() method removes the first item from the list whose value is equal to the passed in argument.
The method raises a ValueError
if there is no such item.
The remove()
method mutates the original list and returns None
.
If you meant to print the contents of the list, use a formatted string literal.
my_list = ['apple', 'banana'] my_str = 'are fruits' result = f'{my_list} {my_str}' print(result) # 👉️ ['apple', 'banana'] are fruits
f
.Make sure to wrap expressions in curly braces - {expression}
.
If you meant to concatenate an item from the list with a string, access the item at the specific index using square brackets.
my_list = ['apple', 'banana'] my_str = ' is my fav fruit' result = my_list[0] + my_str print(result) # 👉️ 'apple is my fav fruit'
We accessed the list element at index 0
, which is a string, so we were able to
concatenate the two strings.
If you aren't sure what type of object a variable stores, use the built-in
type()
class.
my_list = ['apple', 'banana'] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ True my_str = 'are fruits' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True
The type class returns the type of an object.
The isinstance
function returns True
if the passed in object is an instance or a subclass of
the passed in class.