user2963028
user2963028

Reputation: 35

python how to swap some numbers in a list

for example, I have a list[8,9,27,4,5,28,15,13,11,12]

I want to change the position between the numbers after 28 and the numbers before 27. The output should be [15,13,11,12,27,4,5,28,8,9].

I tried to change it, use a,b=b,a , but it doesn't work, there always lost some numbers in the output.

if I only change the position between two numbers, a,b=b,a is working, but if I want to change two or more numbers, it is not working.

could anyone give me some hints plz?

Upvotes: 0

Views: 83

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

You can use slicing:

lis = [8,9,27,4,5,28,15,13,11,12]
ind1 = lis.index(27)
ind2 = lis.index(28)
if ind1 < ind2:
    lis = lis[ind2+1:] + lis[ind1:ind2+1] + lis[:ind1]
else:
    #do something else
print lis
#[15, 13, 11, 12, 27, 4, 5, 28, 8, 9]

Upvotes: 0

Owen
Owen

Reputation: 1736

x = [8,9,27,4,5,28,15,13,11,12]
y = x[6:] + x[2:6] + x[0:2]

>>> y
[15, 13, 11, 12, 27, 4, 5, 28, 8, 9]

Upvotes: 1

Related Questions