Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic Circular List

Tags:

python

list

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?

like image 210
john Avatar asked Jan 21 '12 05:01

john


People also ask

How do you print a circular list in Python?

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.

Can you loop a list in Python?

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.

How do I use an iterator in python?

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.


1 Answers

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)] 
like image 94
voithos Avatar answered Sep 29 '22 19:09

voithos