sam
sam

Reputation: 19

How can i reverse slice of list in Python? At each step we invert an interval of the list and output the entire list

At each step we invert an interval of the list and output the entire list.

input:

3: number of member of list
1 2 3 :list's members
3 :number of indexes of list
2 3: index
2 2: index
2 3: index

output:

1 3 2
1 3 2
1 2 3

Code:

n=int(input())
a = [i for i in map(int,input().split())]
q=int(input())
for i in range(1,q+1):
    l=[i for i in map(int,input().split())]
    a[::-1]
    print(a)

Upvotes: 1

Views: 379

Answers (2)

kederrac
kederrac

Reputation: 17322

from what I understand from the title :

How can i reverse slice of list in Python? At each step we invert an interval of the list and output the entire list

you want to reverse a subsequence from a list, here is an example of how you can do it:

my_list = [1, 2, 3, 4, 5]
start, stop = 1, 4

my_list[start: stop] = my_list[start: stop][::-1]

print(my_list)

output:

[1, 4, 3, 2, 5]

Upvotes: 0

Shubham Sharma
Shubham Sharma

Reputation: 71689

I suppose you might want to do something like this,

mem = int(input("Number of members: "))
members = [int(i) for i in input("List members: ").split()]
idx = int(input("Number of indexes: "))
indexes = [tuple(map(int, input("index: ").split())) for i in range(idx)]

for a, b in indexes:
    members[a - 1], members[b - 1] = members[b - 1], members[a - 1]
    print(members)

Input:

Number of members: 3
List members: 1 2 3
Number of indexes: 3
index: 2 3
index: 2 2
index: 2 3

Output:

[1, 3, 2]
[1, 3, 2]
[1, 2, 3]

Upvotes: 1

Related Questions