-1

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.

Abdul Hoque Nuri
  • 1,105
  • 1
  • 9
  • 18
Iansberg
  • 89
  • 1
  • 1
  • 6

4 Answers4

4

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)
Ayush Kesarwani
  • 518
  • 6
  • 18
  • 1
    I just did this myself and it worked, came back here and saw what people said and here you are! Thanks much! – Iansberg Dec 20 '18 at 19:09
1

Change your code a little, notice the square brackets:

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])

Note it actually gives you a list, i.e. [5,2,3,4,1], not a tuple (5,2,3,4,1).

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
  • 2
    type(seq)([first]+mid+[last]) to make it a tuple when necesarry although I think a if is just much better –  Dec 20 '18 at 05:47
0

You can use list.extend():

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]
    merged = []
    merged.extend(first)
    merged.extend(mid)
    merged.extend(last)
    return merged
Shariq
  • 513
  • 4
  • 14
0

You could just swap the elements

def swap(l):
     temp = l[0]
     l[0] = l[-1]
     l[-1] = temp
     return l
dadrake
  • 112
  • 7