Python (Scripting) - Resolve "TypeError: cannot concatenate 'str' and 'list' objects"

by
Jeremy Canfield |
Updated: January 02 2024
| Python (Scripting) articles
Let's say you try to do something like this, where the fruits list contains a few items, and you try to use the print statement.
#!/usr/bin/python
fruits = ["apple", "banana", "orange", "grapes"]
print ("The fruits lsit contains: " + fruits)
This should cause something like this to be returned.
Traceback (most recent call last):
File "/home/c065234/testing.py", line 3, in <module>
print("The fruits list contains: " + fruits)
TypeError: cannot concatenate 'str' and 'list' objects
This occurs because the print statement contains both a string, which is the text "The fruits list contains: " and a list (the fruits list). This can be resolved by using the str function to convert the fruits list into a string object.
#!/usr/bin/python
fruits = ["apple", "banana", "orange", "grapes"]
print ("The fruits list contains: " + str(fruits))
Or better yet, use Python3 f-string formatter.
#!/usr/bin/python3
fruits = ["apple", "banana", "orange", "grapes"]
print (f"The fruits list contains: {fruits}")
Which should now return the following.
The fruits list contains: ['apple', 'banana', 'orange', 'grapes']
Did you find this article helpful?
If so, consider buying me a coffee over at