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
Related
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])
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
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
I was working on a list and I noticed something.
For example, this piece of code is deleting odd numbers from a list while looping over it.
numbers=[x for x in range (100)]
for nb in numbers:
if nb%2 == 1:
del numbers[numbers.index(nb)]
When you add a counter to see the total iterations you get:
numbers=[x for x in range (100)]
counter=0
for nb in numbers:
if nb%2 == 1:
del numbers[numbers.index(nb)]
counter +=1
The result is counter = 51.
However, if you add the operator list() on the for loop:
numbers=[x for x in range (100)]
counter=0
for nb in list(numbers):
if nb%2 == 1:
del numbers[numbers.index(nb)]
counter +=1
This time the result is counter = 100.
I would like to know why and what is the role of the operator list() here.
Note: if you print numbers and list(numbers) they are identical.
Your second example makes a copy of the list. You iterate through that copy, which remains at 100 elements regardless of what you do to numbers in the meantime.
Your first example alters the list as you iterate through it, a well-documented and well-know bad idea. If you print the list and current value of nb on each iteration, you'll see how the progression works. A simplistic view is that the Python interpreter walks through the list by index (position); when you shorten the list, everything shifts down one position, but that index still increments, thus skipping over one item.
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.
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.