Search code examples
pythonobject-slicing

Python returns first and last item of a sequence exchanged


I need to create a function to slice a sequence in order that first and last item is exchanged and the middle stays in the middle. It needs to be able to handle string/list/tuples. I am having trouble with typeerrors - cant add list + int.

This:

def exchange_first_last(seq):
    """This returns the first and last item of a sequence exchanged"""
    first = seq[-1]
    mid = seq[1:-1]
    last = seq[0]
    return print(first+mid+last)

produces

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

But I don't want a list inside a tuple, just one flowing sequence.

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

Any hints/suggestions welcome. The idea is to slice properly in order to handle different object types.


Solution

  • Try this:

    def exchange_first_last(seq):
        """This returns the first and last item of a sequence exchanged"""
        first = seq[-1:]
        mid = seq[1:-1]
        last = seq[:1]
        return print(first+mid+last)