Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access all list elements from last to first in python list [duplicate]

Tags:

python

list

I have a list of 1000 elements. How do I access all of them starting from last element to the first one in a loop.

list = [4,3,2,1]
for item in list:
    print(from last to first)

output = [1,2,3,4]

like image 693
Rakesh Nittur Avatar asked Mar 15 '23 01:03

Rakesh Nittur


2 Answers

Try:

list = [4,3,2,1]

print [x for x in list[::-1]]

Output:

[1, 2, 3, 4]
like image 52
Andrés Pérez-Albela H. Avatar answered Apr 19 '23 22:04

Andrés Pérez-Albela H.


list = [4,3,2,1]

print [i for i in list[::-1]]

Which gives the desired [1, 2, 3, 4]

like image 21
Inkblot Avatar answered Apr 19 '23 22:04

Inkblot