Skip to content Skip to sidebar Skip to footer

Swapping List With Index

Just want to ask how do i swap the list at the index with the list that follows it and if the list at the index is on the bottom, swap that with the top. So that the index would sw

Solution 1:

defswap(lst, swap_index):
    try:
        next_index = (swap_index + 1) % len(lst)
        lst[swap_index], lst[next_index] = lst[next_index], lst[swap_index]
    except IndexError:
        print"index out of range"
lst = [1,2,3,4]
swap_index = 4
swap(lst,swap_index)
print lst

pay attention that everything in Python is reference, that is to say, the swap function swap elements in place

Solution 2:

I threw together a quick function which should work with any values, though Hootings way may be better.

defitatchi_swap(x, n):
    x_len = len(x)
    ifnot0 <= n < x_len:
        return x
    elif n == x_len - 1:
        return [x[-1]] + x[1:-1] + [x[0]]
    else:
        return x[:n] + [x[n+1]] + [x[n]] + x[n+2:]

And slightly modified to mutate the list:

defitatchi_swap(x, n):
    x_len = len(x)
    if0 <= n < x_len:
        if n == x_len - 1:
            v = x[0]
            x[0] = x[-1]
            x[-1] = v
        else:
            v = x[n]
            x[n] = x[n+1]
            x[n+1] = v

Post a Comment for "Swapping List With Index"