Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

How can I do the following in Python?

array = [0, 10, 20, 40]

for (i = array.length() - 1; i >= 0; i--)

I need to have the elements of an array, but from the end to the beginning.

1 Answer

0 votes
by (106k points)
edited by

Actually, to reverse any list in Python we have many ways and many efficient ways than other languages:-

The first thing you can use the reverse function which is in build function to reverse any data types in Python:-

array=[0,10,20,40] 

for i in reversed(array):

print(i)

image

Important point to note is, the reversed() function does not return a list. Do get a reversed key you can use list(reversed(array)).

array=[0,10,20,40] 

print(list(reversed(array))

image

The second method to do this problem which makes Python unique and best at the work compared to other language is by using the slice method:-

L = [0,10,20,40] 

L[::-1] 

image

To know more about this you can have a look at the following video tutorial:-

If you are looking for upskilling yourself in python you can join our Python Certification and learn from the industrial expert!

Related questions

0 votes
1 answer
asked Feb 19, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...