Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix TypeError: can only concatenate str (not "list") to str

I am trying to lean python from the python crash course but this one task has stumped me and I can’t find an answer to it anywhere

The task is Think of your favorite mode of transportation and make a list that stores several examples Use your list to print a series of statements about these items

cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi'] 

print("I like the "+cars[0]+" ...")

I’m assuming that this is because I have letters and numbers together, but I don’t know how to produce a result without an error and help would be gratefully received The error I get is

TypeError: can only concatenate str (not "list") to str**

like image 264
Nezz Avatar asked May 26 '19 11:05

Nezz


2 Answers

new_dinner = ['ali','zeshan','raza']
print ('this is old friend', new_dinner)

use comma , instead of plus +

If you use plus sign + in print ('this is old friend' + new_dinner) statement you will get error.

like image 148
Mudassar Ahmad Avatar answered Nov 05 '22 09:11

Mudassar Ahmad


Your first line actually produces a tuple of lists, hence cars[0] is a list.

If you print cars you'll see that it looks like this:

(['rav4'], ['td5'], ['yaris'], ['land rover tdi'])

Get rid of all the square brackets in between and you'll have a single list that you can index into.

like image 25
JohnO Avatar answered Nov 05 '22 09:11

JohnO