-1
x = [1, 2, 3, 4, 5, 6, 7, 8]

for num in range(len(x)):  
    x[num] = x[-(num + 1)]
print(x)

Guys I want to know why the code above could not modify the list in reverse order. I am getting [8, 7, 6, 5, 5, 6, 7, 8] when I run the code . Please kindly assist

Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33

2 Answers2

1

To reverse the string, all you need to do is mylist.reverse() or mylist[::-1]. For more details on this, please see Stack Overflow response from last year.

x = [1, 2, 3, 4, 5, 6, 7, 8]

x = x[::-1]

Original list:

[1, 2, 3, 4, 5, 6, 7, 8]

Updated list:

[8, 7, 6, 5, 4, 3, 2, 1]
Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33
0

You are replacing existing values, and then looping back over them. What you want to use is the reverse method.

x = [1, 2, 3, 4, 5, 6, 7, 8]
x.reverse()
print(x)
will-hedges
  • 1,254
  • 1
  • 9
  • 18