Traverse a list in reverse order in Python
Use the built-in reversed()
function:
>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
... print(i)
...
baz
bar
foo
To also access the original index, use enumerate()
on your list before passing it to reversed()
:
>>> for i, e in reversed(list(enumerate(a))):
... print(i, e)
...
2 baz
1 bar
0 foo
Since enumerate()
returns a generator and generators can't be reversed, you need to convert it to a list
first.
How to traverse a list in reverse order in Python (index-style: '... in range(...)' only)
Avoid looping with range, just iterate with a for loop as a general advice.
If you want to reverse a list, use reversed(my_list)
.
So in your case the solution would be:
my_list = reversed([array0,array1,array2,array3])
That gives you [array3, array2, ...]
For omitting the last array from the reversed list, use slicing:
my_list = reversed([array0,array1,array2,array3])[:-1]
So your code turns to a one liner :-)
How to loop a list in reverse order and skip last element
You need to begin from -2
as -1
starts from the last element:
for i in x[-2::-1]:
print(i)
Alternatively, you can use reversed
with list slicing:
for i in reversed(x[:-1]):
print(i)
How do I reverse a list or loop over it backwards?
To get a new reversed list, apply the reversed
function and collect the items into a list
:
>>> xs = [0, 10, 20, 40]
>>> list(reversed(xs))
[40, 20, 10, 0]
To iterate backwards through a list:
>>> xs = [0, 10, 20, 40]
>>> for x in reversed(xs):
... print(x)
40
20
10
0
Print a list in reverse order with range()?
use reversed()
function:
reversed(range(10))
It's much more meaningful.
Update:
If you want it to be a list (as btk pointed out):
list(reversed(range(10)))
Update:
If you want to use only range
to achieve the same result, you can use all its parameters. range(start, stop, step)
For example, to generate a list [5,4,3,2,1,0]
, you can use the following:
range(5, -1, -1)
It may be less intuitive but as the comments mention, this is more efficient and the right usage of range for reversed list.
Need to iterate over a Python list in reverse as fast as possible
>>> from timeit import Timer
>>> t = Timer('[x for x in l[::-1]]', 'l = list(range(100000))')
>>> t.timeit(number=1000)
5.549649953842163
>>> t = Timer('l.reverse(); [x for x in l]', 'l = list(range(100000))')
>>> t.timeit(number=1000)
4.548457145690918
>>> t = Timer('[x for x in reversed(l)]', 'l = list(range(100000))')
>>> t.timeit(number=1000)
4.428632974624634
Conclusion: reversed() is marginally faster than l.reverse() on a list with 100000 items.
This of course is even more true if you don't actually loop over the whole list, and it stops being true if you use the list more than once.
l[::-1]
is outdated since 2.4 that introduced reversed()
.
How to loop backwards in python?
range()
and xrange()
take a third parameter that specifies a step. So you can do the following.
range(10, 0, -1)
Which gives
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
But for iteration, you should really be using xrange
instead. So,
xrange(10, 0, -1)
Note for Python 3 users: There are no separate
range
andxrange
functions in Python 3, there is justrange
, which follows the design of Python 2'sxrange
.
Related Topics
Unicodedecodeerror: 'Ascii' Codec Can't Decode Byte 0Xef in Position 1
Argument 1 Has Unexpected Type 'Nonetype'
Is There a Math Ncr Function in Python
Finding Multiple Occurrences of a String Within a String in Python
Error When Configuring Tkinter Widget: 'Nonetype' Object Has No Attribute
How to Count Occurrence of Unique Values Inside a List
"Cannot Open Include File: 'Config-Win.H': No Such File or Directory" While Installing MySQL-Python
Execute Multiple Commands in Paramiko So That Commands Are Affected by Their Predecessors
How to Copy an Entire Directory of Files into an Existing Directory Using Python
Converting Dict to Ordereddict
How to Plot Multiple Seaborn Jointplot in Subplot
How to Set Environment Variables in Pycharm
Not Letting the Character Move Out of the Window
Python CSV Error: Line Contains Null Byte
Why Is My Pygame Display Not Responding While Waiting for Input