0

I'm a beginner at programming Python and came across this program.

This algorithm is used to reverse a list:

mylist = [1,2,3,4]
reverse = mylist[:]
for i in range(len(reverse)//2):
    reverse[i], reverse[len(reverse) -i -1] = reverse[len(reverse) -i -1], reverse[i]

This algorithm is based on the logic that the swapping process will happen only till the len/2 element for lists with even lengths or the len/2 element in case of lists with a odd length because if the swapping process occurred till the last element, the list would remain the same as it was in the beginning.

I understood what the below part does, but how do I derive it, please explain the logic:

reverse[len(reverse) -i -1]
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

0

len(reverse) returns the number of elements the list has. To actually use it as an index you need to subtract 1 from it as indices start from 0. Next, we also subtract i from it as we are moving i positions away from both ends of the list and swapping them.

So if i=1 reverse[i] points to 2 while reverse[len(reverse)-i-1 points to 3.

Saatvik Ramani
  • 392
  • 3
  • 8
0

You can just print the contents of these variables:

lst = [1, 2, 3, 4, 5, 6]
for i in range(len(lst)//2):
    print(i, len(lst) - i - 1)

This will print

0 5
1 4
2 3

Therefore,

  • for the index of the first element (i = 0), len(lst) - i - 1 will return the index of the last element (i = 5).

  • for the index of the second element (i = 1), len(lst) - i - 1 will return the index of the second to last element (i = 4).

And so on.

enzo
  • 9,861
  • 3
  • 15
  • 38