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'
12 Réponses
+ 3
Here is an example how you can do it with while loop.
https://code.sololearn.com/cHyLAA8tdZir/?ref=app
+ 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.
+ 2
Using index method
https://code.sololearn.com/cf9x6R7N9Ths/?ref=app
+ 2
Got it!
All thanks to you Ipang & Tibor Santa
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.
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?
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..
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
0
No problem Amit Dubey 👌
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.
- 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])