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.
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.
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.
How to access previous values inside a loop?
You can keep repeated letters in an array and then check if the letter already exists.
function repeat(){
let str = "helloworld";
let letters = "";
let count = "";
let output = "";
let x = "";
let multipleChars = [];
for (i = 0; i <str.length; i++){
letters = str.charAt(i);
count = str.split(letters).length - 1;
if (count >= 2 && x !== letters && !multipleChars.includes(letters)) {
output += letters +"=" + count + " ";
multipleChars.push(letters);
}
x = letters;
}
console.log(output);
}
repeat();
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])
Related Topics
Pylint "Unable to Import" Error - How to Set Pythonpath
How to Pass a Method as a Parameter in Python
Implementing Slicing in _Getitem_
Seaborn Is Not Plotting Within Defined Subplots
Automatically Import Modules When Entering the Python or Ipython Interpreter
How to Print to Stderr in Python
Python Selenium Accessing HTML Source
How to Check If Type of a Variable Is String
How to Put Individual Tags for a Matplotlib Scatter Plot
Indexerror: Tuple Index Out of Range When Using Py2Exe
Differencebetween Drawing Plots Using Plot, Axes or Figure in Matplotlib
Combining Two Sorted Lists in Python
How to Remove Nan Values from a Numpy Array
Modifying a List Inside a Function
What Does 'Valueerror: Cannot Reindex from a Duplicate Axis' Mean