Home > other >  Changing position of indexes in a list
Changing position of indexes in a list

Time:10-25

what would be the best way of swapping indices of list of undetermined length? I want to swap the positions of the numbers in pairs, so that the first and second numbers are swapped, the third and fourth numbers are swapped, etc. The only way I know how to do it is as such:

   my_list[0], my_list[1] = my_list[1], my_list[0]

But I have no clue how to do so if the list is of undetermined length. A sample list would include [1,2,3,4] and would return [2,1,4,3]. But if it's odd, the last index of the list stays in the same position.

CodePudding user response:

You can use range(start, stop, step) to index by twos. Then apply your existing pattern

my_list = [1, 2, 3, 4]

for i in range(0, len(my_list)-1, 2):
    my_list[i], my_list[i 1] = my_list[i 1], my_list[i]

assert my_list == [2, 1, 4, 3], "swapped okay"

CodePudding user response:

First group the list in tuples of two elements

it = iter(my_list)
grouped = zip(it, it)

Now grouped is an iterator. It yields tuples of two elements.

Then join all the tuples reversing them:

new_list = [y for x in grouped for y in reversed(x)]

This add only pairs. If the list is odd then the last element is not added to new_list. So we put the last element in its place:

new_list[len(mylist)-1] = my_list[-1]

If it was already there nothing changes.

The first part (grouping) is rather obscure, but not difficult to understand. zip takes elements from each iterator in its arguments in turn and group them in tuples. But in this case I put the same iterator twice, so when zip takes the second iterator (which is the same as the first) it has already advance a place. So it groups in tuples of two elements because there are 2 iterators, but the elements are those from the unique iterator in order.

  • Related