0 votes
1 view
in Python by (47.8k 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 (107k 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:-

Related questions

0 votes
1 answer
asked Oct 14, 2019 in Python by Sammy (47.8k points)
+1 vote
2 answers
+3 votes
2 answers
0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.8k points)
+2 votes
3 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...