0

This is my list:

 l = [0, 1, 2, 3, 4, 5]

I want to swap adjacent elements, so the list should result in this:

l = [1, 0, 3, 2, 5, 4]

I know that there are lots of solutions for this and I think I found one:

def swap(l):
    return l[::2], l[1::2] = l[1::2], l[::2]

Anyhow I am still getting this Error:

file.py on line 2
    return l[::2], l[1::2] = l[1::2], l[::2]
                           ^
SyntaxError: invalid syntax

Any hints or ideas how to solve this are highly appreciated. (Working on Python2)

mrk
  • 8,059
  • 3
  • 56
  • 78
  • 1
    You can not `return` an assignment statement just an expression. Given you are changing the `l` value itself you probably don't need the `return` statement at all. – AChampion Jun 28 '17 at 18:56
  • Assignment is a statement, not an expression. It cannot be returned, because it doesn't evaluate to a value. – juanpa.arrivillaga Jun 28 '17 at 18:56
  • Wow you guys are fast - thanks, given I want to return the list, is there a way to do that without an additional line? – mrk Jun 28 '17 at 19:01
  • 2
    Note: you are currently only swapping the first 2 elements, swap all elements in the list then you can use slice assignment (note: the list needs to be even length): `l[::2], l[1::2] = l[1::2], l[::2] -> [1, 0, 3, 2, 5, 4]` – AChampion Jun 28 '17 at 19:02
  • 1
    You are modifying in place you probably want to create a new list and return it, e.g. `return [x for pair in zip(*[iter(l)]*2) for x in reversed(pair)]` – AChampion Jun 28 '17 at 19:04
  • Thank you this was very helpful, sorry for the duplicate (I obviously asked the wrong questions while doing my research). – mrk Jun 28 '17 at 19:09

2 Answers2

2

Your code should be

def swap(l):
    l[0], l[1] = l[1], l[0]
Jay Parikh
  • 2,419
  • 17
  • 13
2

Remove the return:

def swap(l):
    l[0], l[1] = l[1], l[0]

You can only return expressions, not full statements.

See here for an explanation of the difference.

Billy
  • 5,179
  • 2
  • 27
  • 53