How to Access the Previous/Next Element in a for Loop

Loop that also accesses previous and next values

This should do the trick.

foo = somevalue
previous = next_ = None
l = len(objects)
for index, obj in enumerate(objects):
if obj == foo:
if index > 0:
previous = objects[index - 1]
if index < (l - 1):
next_ = objects[index + 1]

Here's the docs on the enumerate function.

How to access next element in a list using a for loop

You can use enumerate:

for idx, i in enumerate(nums):
print(i) # print current item
if idx < len(nums) - 1: # check if index is out of bounds
print(nums[idx+1])

Concerning your follow up question on how to handle two elements per list iteration, without repeating any elements, you can use range with a step of 2, e.g.

for idx in range(0, len(nums), 2):
print(nums[idx])
if idx < len(nums) - 1:
print(nums[idx+1])

How to access the next element in for loop in current index/iteration?

You can access any member of the list if you iterate by index number of the array vice the actual element:

for i in range(len(vocab_list)-1):
for j in range(len(sentence)-1):
if(vocab_list[i]==sentence[j] and vocab_list[i+1]==sentence[j+1]):
print "match"

How to access the next and previous items within a foreach iteration over an IEnumerable?

You do your loop as normal, but the item you're currently on becomes next, the previous item is current, and the item before that is prev.

object prev = null;
object current = null;
bool first = true;
foreach (var next in tokens)
{
if (!first)
{
Console.WriteLine("Processing {0}. Prev = {1}. Next = {2}", current, prev, next);
}

prev = current;
current = next;
first = false;
}

// Process the final item (if there is one)
if (!first)
{
Console.WriteLine("Processing {0}. Prev = {1}. Next = {2}", current, prev, null);
}

If you're using C# 7.0+, you can write

(prev, current, first) = (current, next, false);

instead of the three separate statements at the end of the loop.

Get to the previous element in list using for loop

Instead of doing your for loop like this (which is the preferred way)

for element in list:
do_something()

You can do this:

for i in range(len(list)):
element = list[i]
previous_element = list[i-1]
do_something()

Pay attention that in the first iteration, i will be 0 so list[i-1] will give the last element of the list, not the previous, since there is no previous.

In JS how do you access the next object in a for...of loop

Use for loop instead of forof loop. It alows you to check next index of the array and use it as below.

for (let i = 0; i < data.rounds.length; i++) {
const round = data.rounds[i];
const name = r.names.shortName;
let nextRound = data.rounds[i + 1];
if (nextRound) {
// your code here
}
}


Related Topics



Leave a reply



Submit