Python Forum

Full Version: Regarding concatenation of a list to a string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This is the code I wrote initially,

print("Once upon a time, 5 men were walking by the forest")
warriors = ["Kevin", "Casper", "Nick", "Jim", "Napolean"]
print("The names of these men were: " + (warriors))
However, it gives TypeError : can only concatenate str (not "list") to str

So I modified the code this way:

print("Once upon a time, 5 men were walking by the forest")
warriors = ["Kevin", "Casper", "Nick", "Jim", "Napolean"]
print("The names of these men were: " + str(warriors))
And now its working fine, but I don't understand why

It would be great if you could explain this to me.

Thanks
you cannot add objects of different type - str and list.
by the way, it's better to use advanced string formatting methods, rather than convert the list to str and then using +
warriors = ["Kevin", "Casper", "Nick", "Jim", "Napolean"]
print("The names of these men were: {}".format(', '.join(warriors)))
in python 3.6+ you can also use the f-string syntax.
Advanced formatting will be much more handy when it comes to using different types, e.g. numbers
The reason the second version works is that you converted the list to a string with the str() built-in. So you are adding two strings instead of a list and a string.