Jet Alex
Jet Alex

Reputation: 49

Swap list / string around a character 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])

Upvotes: 3

Views: 103

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155363

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]

Upvotes: 5

Related Questions