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
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)
IndexError: list index out of range
next_elem = list1[index+1]
if(index<(len(list1)-1)):
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)
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.

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