Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap list / string around a character python

Tags:

python

I want to swap two parts of a list or string around a specified index, example:

([1, 2, 3, 4, 5], 2)

should return

[4, 5, 3, 1, 2]

I'm only supposed to have one line of code, it works for strings but I get

can only concatenate list (not "int") to list

when I try to use lists.

def swap(listOrString, index):

    return (listOrString[index + 1:] + listOrString[index] + listOrString[:index])
like image 771
Jet Alex Avatar asked May 17 '26 04:05

Jet Alex


1 Answers

It's because you took two slices and one indexing operation and tried to concatenate. slices return sub-lists, indexing returns a single element.

Make the middle component a slice too, e.g. listOrString[index:index+1], (even though it's only a one element slice) so it keeps the type of whatever is being sliced (becoming a one element sequence of that type:

return listOrString[index + 1:] + listOrString[index:index+1] + listOrString[:index]
like image 155
ShadowRanger Avatar answered May 19 '26 04:05

ShadowRanger