Shortest way to *interchange first and last* value of a list [Python]




#def the function to interchange

#We'll do this by creating tuplets and alter the sequence of first and last values on...

#both sides

def interchage(mylist):

    mylist[0], mylist[-1] = mylist[-1], mylist[0]

    return mylist
   
   

given_list = [1, 2, 8, 1, 5, 6]
interchaged_list = interchage(given_list)
print("interchanged list is", interchaged_list)     


OUTPUT: interchanged list is [6, 2, 8, 1, 5, 1]

Now to understand that completely,

Indexing starts from `0` for the first element, and it continues incrementally for
the subsequent elements. So, for a list with six elements, the indices would be:
```
Index:   0   1   2   3   4   5
Value:   1   2   8   1   5   6
```
To access elements from the end of the list, you can use negative indexing. The
negative indices start from `-1` for the last element and continue detrimentally
for the preceding elements. For the same list, the negative indices would be:
```
Index:  -6  -5  -4  -3  -2  -1
Value:   1   2   8   1   5   6
```
So, with the positive indices, you count from `0` to `n-1`
(where `n` is the length of the list), and with negative indices, you count
from `-1` to `-n`.

1 تعليقات

Please leave a review

إرسال تعليق

Please leave a review

أحدث أقدم