Python: Index Out Of Range [duplicate] - python

This question already has answers here:
Removing Item From List - during iteration - what's wrong with this idiom? [duplicate]
(9 answers)
Closed 6 years ago.
I'm new to python and this may be a simple one line or one character answer but I can't seem to wrap my head around it. I have a list I want to iterate through and check if the element in the index after the current index is the same and delete it if it is.
while i < len(list):
if list[i] == list[i+1]:
del list[i];
i+=1;
I know the problem is coming from "if list[i] == list[i+1]:" when I get to end of the list "list[i+1]" will be out of range of the index. The problem is that I don't know how to stop the code when it gets to that point where it goes out of range

Firstly, list is the built-in function of python, so you should never use it for the name of your variables.
And to your problems itself. The fix for your error is simple:
while i < (len(_list) - 1):
if _list[i] == _list[i+1]:
del _list[i]
i+=1;
The reason for the IndexError is that at the last iteration i is already the last index and you are trying to get the element at the i+1 position.

Related

Deleting duplicate elements in a array [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 3 years ago.
I am trying to delete duplicate elements in a array. There are lots of methods out there but I am trying to come up with my own one and tried the folllowing code.
x=[2,1,3,5,3,5]
for i in range(0,len(x)):
for j in range(0,len(x)):
if (x[i]==x[j+1]):
del x[j+1]
for k in range(0,len(x)):
print(x[k])
I get the following error at line 4
list index out of range.
Please help me!
There are two errors I can see:
You are using j+1 in your program. When the second for loop reaches the end of the loop, j would equal 5, and then j+1 would equal 6, but x[6] would be out of bounds.
Deleting the element from the array changes the length of the array. For example, your array starts with a length of 6, but then, after one of the elements is deleted, it instead has a length 5. However, the for loop doesn't recognize this, and still goes until i=5 instead of stopping at i=4, and x[5] is out of bounds.

Hierarchical Searching in a List in Python [duplicate]

This question already has an answer here:
Recursive code returns None [duplicate]
(1 answer)
Closed 6 years ago.
I want to search a Specific Value (an Integer) in a List in Python where the List could possibly have a Hierarchical Structure, So there could be a List on a Specific index (e.g [1,2,[[3,4],[5,6]] here the index 2 is a list it self and there could be a list in that again), and So on, or the index of Original List could have Integer values itself (e.g [1,2,3,[4,5]] in this case index 0 is an integer..
Eventually, I want the index of the searched value w.r.t original List , otherwise if searched value is not in the list, it should give me -1...I'm using recursion for that, but i'm not having the desired results...
Here's My Code
def search_in_list(L,c1):
index=-1
for i in range(len(L)):
if type(L[i])==list:
search_in_list(L[i],c1)
elif type(L[i])!=list:
if c1==L[i]:
index=i
return index
and here's an example List [1,2,[[3,4],[5,6]] So let's say i want to search 6, then it should give me 2 because that's the index of original list on which 6 is present, but i'm having -1 instead...
Can someone dig into my code and tell me the problem and solution...
Thanks in Advance
You can make some modifications to work correctly:
def search_in_list(l, needle):
for i, item in enumerate(l):
if type(item) == list:
# We found it, return current index
if search_in_list(item, needle) >= 0:
return i
else:
if needle == item:
return i
return -1
The main reason it didn't work was in the recursive call. When it returned that the item was found (by returning a non negative index) you didn't return the current index.

Finding the index of an element of a list when you don't know how many occurrences of that element are in the list [duplicate]

This question already has answers here:
Find the index of the second occurrence of a string inside a list
(3 answers)
Find the index of the n'th item in a list
(11 answers)
Closed 7 years ago.
If I'm working with a list containing duplicates and I want to know the index of a given occurrence of an element but I don't know how many occurrences of that element are in the list, how do I avoid calling the wrong occurrence?
Thanks
I don't know that a single builtin does this thing alone, but you could fairly easily write it, for instance:
def index_second_occurence(alist, athing):
if alist.count(athing) > 1:
first = alist.index(athing)
second = alist[first + 1::].index(athing)
return second + first + 1
else:
return - 1

Beginner Python: Deleting elements from a list [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 7 years ago.
I am working of Project Euler problem 2. I need to find the sum of all even Fibonacci numbers up to four million. I have a function that generates all possible Fibonacci numbers up to upperBound which is input by the user. I am passing this list of fibs to another function in order to eliminate the odd values. I am trying to iterate through the list and delete the element if it is odd. It is returning an error saying :
in evenFibs
del list_of_fibs[value]
IndexError: list assignment index out of range
Here is my code for evenFibs() :
def evenFibs(upperBound):
list_of_fibs = getFibs(upperBound)
for value in list_of_fibs:
if value % 2 != 0:
del list_of_fibs[value]
return list_of_fibs
I am not sure why this error is occuring.
Take a note that you shouldn't change array while iterating it, also to delete element from array you should use index of element, not value. You can get index of first element with specific value using index method of list. As for your task, it would be better to use list comprehension:
def evenFibs(upperBound):
list_of_fibs = getFibs(upperBound)
return [value for value in list_of_fibs if value % 2 == 0]

Find index of last item in a list [duplicate]

This question already has answers here:
How to find the last occurrence of an item in a Python list
(15 answers)
Closed 8 years ago.
For example, I have a list
[0,2,2,3,2,1]
I want to find the index of the last '2' that appears in this list.
Is there an easy way to do this?
You can try the following approach. First reverse the list, get the index using L.index().
Since you reversed the list, you are getting an index that corresponds to the reversed, so to "convert" it to the respective index in the original list, you will have to substract 1 and the index from the length of the list.
n = ...
print len(L) - L[::-1].index(n) - 1

Categories