0

How to find the next element after a particular element in a list?

arr = [1,2,3,#,@,5,6,7,8] What i want to do > (pseudo code) For i in range(len(arr)): If arr[i] =='#' and arr[i+1]==@: arr.remove("#") arr.remove("@") else: continue But it gives me error 'index out of range'

4th Apr 2020, 2:51 PM
Amit Dubey
Amit Dubey - avatar
12 Answers
+ 3
Here is an example how you can do it with while loop. https://code.sololearn.com/cHyLAA8tdZir/?ref=app
4th Apr 2020, 4:46 PM
Tibor Santa
Tibor Santa - avatar
+ 3
I believe there are two reasons you would get an "index out of range" error. Firstly, when you do for i in range(len(arr)):, the maximum value of i is equal to one less than the length if arr. So when you do arr[i+1], that index is out of range. Secondly, when you remove elements of your arr list while iterating over it, your loop keeps iterating over the original length of the list.
4th Apr 2020, 3:08 PM
Russ
Russ - avatar
4th Apr 2020, 4:54 PM
Ipang
+ 2
Got it! All thanks to you Ipang & Tibor Santa
5th Apr 2020, 4:13 AM
Amit Dubey
Amit Dubey - avatar
0
Do you really have to remove '#' and '@'? Removing item while traversing its container is tricky business, even worse when you use a ranged for-loop like that. Perhaps use a while-loop instead, so you can alter the loop counter as necessary to jump over unwanted elements. Or you can use `find` or `index` method to locate unwanted substring and make a slice. Still wouldn't recommend item removal even with while-loop.
4th Apr 2020, 3:09 PM
Ipang
0
So what should i do to remove '#' and '@' if they are close to each other in a list? Russ Ipang
4th Apr 2020, 3:49 PM
Amit Dubey
Amit Dubey - avatar
0
Amit Dubey Do you want to create a new list excluding '#' and '@' or you want to print the list content excluding those characters? or do something else?
4th Apr 2020, 3:54 PM
Ipang
0
I want to change that list or create a new list, excluding those characters only if they are next to each other, if they at different indexes then i don't wanna do anything..
4th Apr 2020, 4:02 PM
Amit Dubey
Amit Dubey - avatar
0
Amit Dubey [i+1] is giving you error. Total length of arr cant be exceed. Set your range function to len(arr)-1. Then give it a try
4th Apr 2020, 8:52 PM
Tarun
Tarun - avatar
0
No problem Amit Dubey 👌
5th Apr 2020, 4:32 AM
Ipang
0
You have two way of doing that; 1. By using index() + list slicing. The index() will find the desired element while the list slicing will get the exact element. 2. By using generator. Generator function uses yield to get the elements till the required element then it breaks the yield after the specified element.
6th Apr 2020, 2:42 PM
Bishir Sirajo
Bishir Sirajo - avatar
- 1
Here's a simple code that returns the next element after a list = ["a", "b", "c", "d"] sec_element_index = list.index("a")+1 print (list[sec_element_index])
5th Apr 2020, 8:43 PM
youcef demdoum
youcef demdoum - avatar