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)
Answer from Chinmay Kanchi on Stack OverflowNote for Python 3 users: There are no separate
rangeandxrangefunctions in Python 3, there is justrange, which follows the design of Python 2'sxrange.
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
rangeandxrangefunctions in Python 3, there is justrange, which follows the design of Python 2'sxrange.
for x in reversed(whatever):
do_something()
This works on basically everything that has a defined order, including xrange objects and lists.
bash - How do I reverse a for loop? - Unix & Linux Stack Exchange
For Loop Backwards Help
Reverse For Loop for Components
Reverse Iteration Terminal in For Loop - NI Community
Videos
I'm not finding much about doing a reversed for loop on a slice. Something with this kind of code:
const string: []const u8 = "1234";
for reversed (string) |character| {
std.debug.print("{}", .{character});
}And this output:
4 3 2 1
Is there a language feature I'm not aware of, or a function in the std, or should I just use a plain old dirty while loop?
In bash or ksh, put the file names in an array, and iterate over that array in reverse order.
files=(/var/logs/foo*.log)
for ((i=${#files[@]}-1; i>=0; i--)); do
bar "${files[$i]}"
done
The code above also works in zsh if the ksh_arrays option is set (it is in ksh emulation mode). There's a simpler method in zsh, which is to reverse the order of the matches through a glob qualifier:
for f in /var/logs/foo*.log(On); do bar $f; done
POSIX doesn't include arrays, so if you want to be portable, your only option to directly store an array of strings is the positional parameters.
set -- /var/logs/foo*.log
i=$#
while [ $i -gt 0 ]; do
eval "f=\${$i}"
bar "
((i-1))
done
Try this, unless you consider line breaks as "funky characters":
ls /var/logs/foo*.log | tac | while read f; do
bar "$f"
done