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

Question:

I am trying to learn 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 favourite 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**

Asked By: Nezz

||

Answers:

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.

Answered By: JohnO

This is one of the possibilities you can use to get the result needed.
It learns you to import, use the format method and store datatypes in variables and also how to convert different datatypes into the string datatype!
But the main thing you have to do is convert the list or your wished index into a string. By using str(----) function. But the problem is that you’ve created 4 lists, you should only have one!

from pprint import pprint
cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']
Word = str(cars[0])
pprint("I like the {0} ...".format(Word))
Answered By: Jakub.K

First, create a list (not tuple of lists) of strings and then you can access first element (string) of list.

cars = ['rav4', 'td5', 'yaris', 'land rover tdi']
print("I like the "+cars[0]+" ...")

The above code outputs: I like the rav4 ...

Answered By: xanjay
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.

Answered By: Mudassar Ahmad

You can do like

new_dinner = ['ali','zeshan','raza']
print ('this is old friend', *new_dinner)
Answered By: subhashis

Here you are the answer :

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

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

What we have done here is calling the list first and then calling the first item in the list.
since you are storing your data in a tuple, this is your solution.

Answered By: MertHaddad
    new_dinner = ['ali','zeshan','raza']
    print ('this is old friend', str(new_dinner))

    #Try turning the list into a strang only
Answered By: EE mud
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.