Swap list / string around a character python
<p>I want to swap two parts of a list or string around a specified index, example:</p>

<pre><code>([1, 2, 3, 4, 5], 2)
</code></pre>

<p>should return</p>

<pre><code>[4, 5, 3, 1, 2]
</code></pre>

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

<p>can only concatenate list (not "int") to list</p>

<p>when I try to use lists.</p>

<pre><code>def swap(listOrString, index):

    return (listOrString[index + 1:] + listOrString[index] + listOrString[:index])
</code></pre>

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

<p>Make the middle component a slice too, e.g. <code>listOrString[index:index+1]</code>, (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:</p>

<pre><code>return listOrString[index + 1:] + listOrString[index:index+1] + listOrString[:index]
</code></pre>

python