Computer Science, asked by kkrishnaraj049, 2 months ago

How will you access the list elements in reverse order ?

•python enable reverse or negative indexing for the list element.
•A negative index can be used to access an element in reverse order.
•Thus,python lists index in opposite order.​

Answers

Answered by Aryansingh001
2

Answer:

  1. # Reverse a List with Slicing
  2. names = ['Alice', 'Bob', 'Carl', 'Dora']
  3. names = names[::-1]
  4. print(names)

# ['Dora', 'Carl', 'Bob', 'Alice']

2

Negative indexes are a way to allow you to index into a list, tuple or other indexable container relative to the end of the container, rather than the start.

They are used because they are more efficient and are considered by much more readable.

>>> l = [0,1,2,3,4,5]  

>>> l[-1]  

5  

>>> l[len(l) - 1]  

5  

line 2 and line 4 are functionally equivalent, but line 2 will be significantly quicker.

You can also use negative indexes in slices, and as with positive indexes, when you do a slice operation, the last element is not included in the slice

>>> l = [0,1,2,3,4,5]  

>>> l[-3:-1]  

[3,4]  

As with positive indexes the length of a slice can be calculated by subtracting the start index from the end index - in this case:  −1−(−3)=−1+3=2  as demonstrated.

you can even use negative indexes with negative steps to make a reversed slice :

>>> l = [0,1,2,3,4,5]  

>>> l[-1:-4:-1]  

[5,4,3]  

here the 3rd value in the slice tells Python to go backwards from index -1 (the last element - number 5 here) to index -4 (i.e. 4th from the end - item 2 here), with the final element in the slice omitted.

3

>>> mylist = [1, 2, 3, 4, 5]

>>> mylist

[1, 2, 3, 4, 5]

>>> mylist.reverse()

None

>>> mylist

[5, 4, 3, 2, 1]

Explanation:

i will feel good if  it helps u  if coz it,s ur 1st question btw nice dp my  FF id is evilary100

plz mark me as abrainliest

Similar questions