Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping two sublists in a list

Tags:

python

list

Given the following list:

my_list=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

I want to be able to swap the sub-list my_list[2:4] with the sub-list my_list[7:10] as quickly and as efficiently as possible, to get the new list:

new_list=[0, 1, 7, 8, 9, 4, 5, 6, 2, 3, 10, 11, 12]

Here's my attempt:

def swap(s1, s2, l):

    seg1=l[:s1.start]+l[s2]
    seg2=l[s1.stop : s2.start]
    seg3=l[s1]+l[s2.stop:]

    return seg1+seg2+seg3


print swap(slice(2,4), slice(7,10), [0,1,2,3,4,5,6,7,8,9,10,11,12])

This does print the desired output, although this way of doing it looks awful to me.

Is there a more easy and elegant way of doing it, that will not create four new lists for every function call? (I plan to call this function a lot)

I don't mind (actually I'd prefer) changing the original list, rather than creating new instance every function call.

like image 363
so.very.tired Avatar asked Jun 29 '15 08:06

so.very.tired


People also ask

How do you switch two items in a list in Python?

To swap two list elements x and y by value, get the index of their first occurrences using the list. index(x) and list. index(y) methods and assign the result to variables i and j , respectively. Then apply the multiple assignment expression lst[i], lst[j] = lst[j], lst[i] to swap the elements.

Can you swap items in a list Python?

Given a list in Python and provided the positions of the elements, write a program to swap the two elements in the list. Since the positions of the elements are known, we can simply swap the positions of the elements.

How do you sub a list in Python?

To get the subarray we can use slicing to get the subarray. Step 1: Run a loop till length+1 of the given list. Step 2: Run another loop from 0 to i. Step 3: Slice the subarray from j to i.

Can a list be sliced into Sublists Python?

Given a list of lists and list of length, the task is to split the list into sublists of given length. Method #1: Using islice to split a list into sublists of given length, is the most elegant way. # into sublists of given length. Method #2: Using zip is another way to split a list into sublists of given length.


1 Answers

Slices can be assigned.

Two variables can be swapped with a, b = b, a.

Combine the two above::

>>> my_list[7:10], my_list[2:4] = my_list[2:4], my_list[7:10]
>>> my_list
[0, 1, 7, 8, 9, 4, 5, 6, 2, 3, 10, 11, 12]

Beware that - if slices have different sizes - the order is important: If you swap in the opposite order, you end up with a different result, because it will change first the initial items (lower indices), and then the higher index items (but those will be shifted in a different position by the first assignment).

Also, slices must not overlap.

like image 167
fferri Avatar answered Sep 19 '22 11:09

fferri