+2 votes
in Programming Languages by (14.6k points)

The following code gives error: "TypeError: must be str, not list"

>>> i=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'y']

>>> id = i[-1] + i[:-1]

What is wrong with this code?

1 Answer

0 votes
by (25.6k points)

As per the error, you are trying to add a list to a string. Python cannot add them and hence it's giving the error.

i[-1] is the last element of your list, which is 'y' and i[:-1] is a list. If you want to put the last element in the first position in your new list, you can do the following:

>>> id = [i[-1]] + i[:-1]  #Add [] to make it a list
>>> id
['y', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

...