PYTHON PROGRAMMING LANGUAGE / ITERATION

Accessing Next Element While iterating | Python Tips

To get the next element while iterating through an iterator.

Image for post
Image for post
©iambipin

hough it might sound too easy, in reality, there are some complications while accessing the next element when iterating through an iterator in Python. It is often said that some of the simplest things in life are the hardest ones to achieve. Errors galore as you show complacency. Let’s analyze to understand better.

Consider a Python list(an ordered sequence of items that are mutable):

list1 = [1, 8, 3, 4, 9, 6]

Suppose you have to create a new list from list1 such that each element is obtained by adding the element and its adjacent right element. So the first element will be 1+8=9. The last element will be 6+0=6(as there is no element to its right).In such a scenario, you want to access the very next element while iterating through the list and add it to the current element. It might appear very simple although it isn’t as easy as it seems. Let’s code to find out:

list1 = [1, 8, 3, 4, 9, 6]
new_list = []
for index, elem in enumerate(list1):
current_elem = elem
next_elem = list1[index+1]
new_list.append(current_elem + next_elem)

print(new_list)

You might think you got the results, however, you will end up with the IndexError:

IndexError: list index out of range

The list has 6 elements(index ranging from 0 to 5). As we reach the last element, the index is 5. So when the following addition operation is done, the list index goes out of range:

next_elem = list1[index+1]

The IndexError can be rectified by incorporating the following condition:

if(index<(len(list1)-1)):

Hence the last time the condition check will be performed for the penultimate element.

The final code:

new_list = []
for index, elem in enumerate(list1):
if(index<(len(list1)-1)):
new_list.append(elem + list1[index+1])
else:
new_list.append(elem)

print(new_list)

We can merge these lines of code to a single line using List Comprehension:

new_list = [elem+list1[index+1] if(index<(len(list1)-1)) else elem for index, elem in enumerate(list1)]
print(new_list)
Output:
[9, 11, 7, 13, 15, 6]

Use case

You might be wondering why all the fuss about a simple problem. The simple reason being that the same logic will find application in more complex problems. Let’s consider the binary numbers problem in Hackerrank.

The objective is to find the maximum number of consecutive 1’s in the binary number(base-2 representation) of a decimal number(base-10 representation). As it involves counting the number of consecutive 1’s, we must access the next element while iterating through the loop. So when two ones appear consecutively, a counter must be incremented. Hence, an input of 6 will have an output of 2. The real test lies when you are given input like 13(1101) or 103(1100111) or 524275(1111111111111110011). If you have not implemented code with appropriate condition checks, you will get erroneous output for them(e.g., 3 for 13 or 5 for 103).

To know more about HackerRank Binary Problem, kindly visit my blog here:

To know more about decimal to binary conversion, kindly visit my blog here:

Hope you learned something new. Happy Coding!!!

Written by

Data Science Enthusiast striving to secure greater goals

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store