Loop Backwards Using Indices

Loop backwards using indices

Try range(100,-1,-1), the 3rd argument being the increment to use (documented here).

("range" options, start, stop, step are documented here)

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 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 and xrange functions in Python 3, there is just range, which follows the design of Python 2's xrange.

How to make reversed for loop with array index as a start/end point in Kotlin?

You can loop from the last index calculated by taking size - 1 to 0 like so:

for (i in array.size - 1 downTo 0) {
println(array[i])
}

Even simpler, using the lastIndex extension property:

for (i in array.lastIndex downTo 0) {
println(array[i])
}

Or you could take the indices range and reverse it:

for (i in array.indices.reversed()) {
println(array[i])
}

Iterate List in Reverse from a specific Index

You can use Collections.rotate in combination with Collections.reverse with out the need of a new list or a for loop:

public static void main(String[] args) {
//original: 4 5 8 7
//expected: 8 5 4 7

List<Integer> mylist = new ArrayList<>(Arrays.asList(4,5,8,7));
System.out.println("Original List : " + mylist);

int distance = mylist.indexOf(8) + 1;
Collections.reverse(mylist);
Collections.rotate(mylist, distance);

System.out.println("Rotated List: " + mylist);
}

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 :-)

What's the best way to do a backwards loop in C/C#/C++?

While admittedly a bit obscure, I would say that the most typographically pleasing way of doing this is

for (int i = myArray.Length; i --> 0; )
{
//do something
}


Related Topics



Leave a reply



Submit