my swap function is not working in python

Viewed 88

please guys, this function is meant to swap a group of items in a list, like the first k items with the last k items, but I dont know how to get the function to work

 def swap(L, k):
     L[len(L)-k:], L[:k] = L[:k], L[len(L)-k:]

yet when I run this with doctest, it fails

swap([1, 2, 3, 4, 5, 6],2)
3 Answers

Fix the indexes, return a list from the method, and print the resulting list:

def swap(L, k):
     return L[(-k):] + L[k:(-k)] + L[:k]

lst = swap([1, 2, 3, 4, 5, 6], 2)
print(lst)     
# [5, 6, 3, 4, 1, 2]

Note that the original list is not modified - what is returned is a different list with elements swapped.

The function works perfectly, but you have no other references to the list you're passing in, so it gets discarded. Simply save the list to a name before passing it in.

By the way, the len(L) is unnecessary.

def swap(L, k):
    """
    >>> lst = [1, 2, 3, 4, 5, 6]
    >>> swap(lst, 2)
    >>> lst
    [5, 6, 3, 4, 1, 2]
    """
    L[-k:], L[:k] = L[:k], L[-k:]
def swap(L, k):
   J = L[:k]
   L[:k] = L[-2:]
   L[-2:] = J
P = [1,2,3,4,5,6]
swap(P,2)
# P ==[5, 6, 3, 4, 1, 2]
Related