Say I have a list,
l = [1, 2, 3, 4, 5, 6, 7, 8]
I want to grab the index of an arbitrary element and the values of its neighbors. For example,
i = l.index(n) j = l[i-1] k = l[i+1]
However, for the edge case when i == len(l) - 1
this fails. So I thought I'd just wrap it around,
if i == len(l) - 1: k = l[0] else: k = l[i+1]
Is there a pythonic way to do this?
Given a list of elements, the task is to print element in group of k till n-iteration in circular range. We can use itertools with zip to do this task. # of 5 till 9 iteration in circular range.
You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.
Iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter() method. It uses the next() method for iteration. next ( __next__ in Python 3) The next method returns the next value for the iterable.
You could use the modulo operator!
i = len(l) - 1 jIndex = (i - 1) % len(l) kIndex = (i + 1) % len(l) j = l[jIndex] k = l[kIndex]
Or, to be less verbose:
k = l[(i + 1) % len(l)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With