stop list updating when using del python [duplicate] - python

This question already has answers here:
error list indices must be integers, not list. Take values of one array use them as indexes to delete values from another array
(3 answers)
Closed 9 years ago.
I have a list where i want to delete certain elements from
I have created a for loop and in this for loop have put del my list[i]
prule is a list of strings containing things like numbers as strings from 0 to 159 its size 11154
def getind(li)
ret = {}
for i, x in enumerate(li):
if x not in ret:
ret[x] = []
ret[x].append(i)
return ret
dups = getind(prule)
for n in dups.get('159',[]):
del rulelines[n]
After a while of doing this list assignment index out of range which I am guessing is because the list gets updated. Is there anything I can use so it doesn't get updated until the for loop is finished

You should browse your list backwards:
for x in range(subjectlength - 1, -1, -1):
del my_list[x]

As I have corrected in my answer here
dups = getind(prules)
indexes = dups.get('156',[])
rulelines = [rulelines[i] for i in range(len(rulelines[:])) if i not in indexes]
Should be what solves your problem.

Related

Python adding to a nested list [duplicate]

This question already has answers here:
Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add (append) elements to a list?
(9 answers)
Closed 4 months ago.
n = int(len(network))
num=[]
for i in range(n):
for j in range(n):
num[i].append(int (between_lists(network[i],network[j])))
return num
this error message I get
num[i].append(int (between_lists(network[i],network[j])))
IndexError: list index out of range
Any of your three indexing operations could be the cause, but num is definitely an empty list, so you can't index it at all. Did you perhaps mean to append to num itself, not to a sublist within num (which has no inner lists at all)?
num.append(int (between_lists(network[i],network[j])))
# ^ removed [i]
Update: Based on your comments, you want a new sublist for each run of the outer loop, so what you really wanted is:
for i in range(n):
num.append([]) # Put in new sublist
for j in range(n):
num[i].append(int(between_lists(network[i],network[j])))
return num

I have written a program to create a list that stores the intersection of two lists. It's showing an error at line 23 [duplicate]

This question already has answers here:
Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add (append) elements to a list?
(9 answers)
Closed 9 months ago.
I'm using an algorithm similar to Merge Sort. Firstly, I'm sorting both the lists. Then, I'm comparing the first element of each sorted list, and adding the smaller element to another list. Here's my code:
leftList=[int (x) for x in input().split()]
rightList=[int (x) for x in input().split()]
output=[]
# print(leftList,rightList)
leftList.sort()
rightList.sort()
# print(leftList,rightList)
i=j=k=0
# Until we reach the end of either leftList or rightList, pick the smaller of
# leftList[i] and rightList[j], and place it in the correct position in output[]
while i<len(leftList) and j<len(rightList):
if leftList[i]<=rightList[j]:
output[k]=leftList[i]
i+=1
else:
output[k]=rightList[j]
j+=1
k+=1
# When we run out of elements in either leftList or rightList,
# place the remaining elements in output[]
while i<len(leftList):
output[k]=leftList[i]
i+=1
k+=1
while j<len(rightList):
output[k]=rightList[j]
j+=1
k+=1
print(output)
Here's the error that I'm getting:
---> 23 output[k]=rightList[j]
IndexError: list assignment index out of range
Please help!
In python, you can't set a list value you haven't initialised as you can in other languages. This means that, if I do something like mylist[3] = 4, the length of mylist must be at least 4 before the assignment, and the assignment can't make some slots magically appear.
So, instead of incrementing a k counter, just replace all occurences of output[k] = ... with output.append(...).
Your problem is at this line:
output[k]=rightList[j]
Your list is empty and cannot access the first element. The best way to insert would be the append method:
output.append(rightList[j])

did I did something wrong with list and for loop in python? [duplicate]

This question already has answers here:
Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add (append) elements to a list?
(9 answers)
Closed 1 year ago.
the thing that I am supposed to do is,
get 10 int
find the different value after doing %42 for those 10 input int
and what I thought is, like this
n = []
for i in range(10):
a = int(input())
n[i] = a%42
s = set(n)
print(len(s))
but it didn't work with a message of
----> 4 n[i] = a%42
IndexError: list assignment index out of range
and by googling I have solved this question by adding append.
n = []
for i in range(10):
a = int(input())
print("a",a)
b = a%42
print("b",b)
n.append(b)
s = set(n)
print(len(s))
** here is my question. why did my code didn't work? I thought my method's logic is solid. Is there some knowledge that I am missing about? **
thank you previously.
actually when you were trying first way you were using lists built-in dunder(magic method) which asks that there must be an element at that index before changing its value, meanwhile list is empty and hence it can't find an element whose value has to be chanced but append works something like this:
yourList += [newElement]
which is basically like list concatination.
Your code doesn't work because n is an empty list so it has no sense to assign a value to an index.
If you know the size of your list you can do:
# this works
n = [size]
n[0] = 1

Python - Work with everything in the list one by one [duplicate]

This question already has answers here:
Apply function to each element of a list
(4 answers)
What are iterator, iterable, and iteration?
(16 answers)
Closed 6 months ago.
I have a list my_list = []
In this list are some int's so my_list = [1,2,3,4]
Now I want to work with every number one by one, without knowing there are only 4 int's. There could be 1000 things in the list. I thought about sth like:
i = len(self.my_list)
while i > 0:
print(my_list[i])
i -=1
but I got this error: IndexError: list index out of range
What you could do is iterate over each item in the list:
for i in my_list:
print(i,i**2)
I usually using this method:
my_list = [1,2,3,4]
i=0
while(i < len(my_list)):
print(my_list[i])
i+=1
with while you have control of index.

Function that takes a list and returns a list with only unique elements from the original? [duplicate]

This question already has answers here:
How do I remove duplicates from a list, while preserving order?
(30 answers)
Closed 6 years ago.
I am working my way through the Think Python Textbook, and one of the problems it gives is to make a function that takes a list and returns a list with only unique elements from the original. What I have so far is this:
def remove_duplicates(l):
index = 0
new_l = []
dup_l = []
while index < len(l):
if l[index] in l[index+1:] or l[index] in new_l:
dup_l += [l[index]]
index = index + 1
elif l[index] in dup_l:
index = index + 1
else:
new_l += [l[index]]
return new_l
I feel like there must be a more succinct, pythonic way to write this function. Can somebody help this beginner programmer?
I assume you want to do it manually, to understand python syntax so this is a way of doing it.
Update for the comment made about only getting elements that occur only once and not removing duplicates, you can replace the if condition to if L.count(element) == 1: and it will return [1,2,4] as you were requesting.
def unique(L):
uniqueElements = []
for element in L:
if element not in uniqueElements:
uniqueElements.append(element)
return uniqueElements
print(unique([1,2,3,3,4]))
And if you want to delve further into the python syntax, you could do a list comprehension and simplify it further, while still not using the set method which loses the order of elements:
def unique(L): return [element for element in L if L.count(element) == 1]

Categories