Lily Filsell - 9 months ago 28

Python Question

I'm trying to design a code that will reverse a given list at the index of a given value. The rest of the list beyond the value will be printed in correct order, but I can't seem to complete it.

This is the code I have so far.

`def reverse(my_list, value):`

lst = []

lst2 = []

for x in range(my_list[0], my_list[value]):

x = my_list[x]

lst2.append(x)

for i in range(len(lst2)-1, -1, -1):

x = lst2[i]

lst.append(x)

for x in range(my_list[value], len(my_list)):

x = my_list[x]

lst.append(x)

print(lst)

If the input is this.

`reverse([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)`

The output should be.

`[5, 4, 3, 2, 1, 6, 7, 8, 9, 10]`

But instead the output is this.

`[6, 5, 4, 3, 2, 7, 8, 9, 10]`

Can anyone help me to determine how to get the needed output?

Answer Source

Indexes in first and third cycles are wrong, you have to iterate through indexes not values. Write like here:

```
def reverse(my_list, value):
lst = []
lst2 = []
for x in range(0, value):
x = my_list[x]
lst2.append(x)
for i in range(len(lst2)-1, -1, -1):
x = lst2[i]
lst.append(x)
for x in range(value, len(my_list)):
x = my_list[x]
lst.append(x)
print(lst)
reverse([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)
```

output: [5, 4, 3, 2, 1, 6, 7, 8, 9, 10]