How to access the next element from a unique list in Python

Viewed 1230

I have a list in Python

lst=['a', 'b', 'c', 'd', 'e', 'f']

What is the best way to access the next element in the list for a given value.

For instance I would like to get:

next_element(lst, 'c')
# 'd' should return adjacent value of 'c'

What is the Pythonian way of doing it?

3 Answers

You can use the next() built-in function:

some_list = ['a', 'b', 'c', 'd', 'e', 'f']

random_iterator = iter(some_list)

print(next(random_iterator)) #Output = a

print(next(random_iterator)) #Output = b

The syntax of next() is:

next(iterator, default)
  1. iteratornext() retrieves next item from the iterator
  2. default (optional) — this value is returned if the iterator is exhausted (there is no next item)

  1. The next() function returns the next item from the iterator.
  2. If the iterator is exhausted, it returns the default value passed as an argument.
  3. If the default parameter is omitted and the iterator is exhausted, it raises StopIteration exception.

This function should do what you want it to - I think utilizing the index method would be the most pythonian way to solve your issue - although I could be wrong, this is just how I thought about it.

def next_element(lst, element):
   idx = lst.index(element)
   return lst[idx +1]

Here is a simple way to do it

def next_element(l, elt):
    return l[l.index(elt)+1]

This will throw an error if the element passed into the function is the last one in the list. You might want to add some logic to handle that, depending on what you desire. Additionally, this assumes that all elements in the list are unique.

This solution however, will be very slow for a large list. list.index searches the list element by element until it finds the right elements, so it runs in O(n). If you are trying to walk through a list but don't want to use a loop, you can create an iterator to walk through the list as you need to.

lst = ['a', 'b', 'c', 'd', 'e', 'f']
myit = iter(lst)
next(myit) # will return 'a'
next(myit) # will return 'b'
Related