Python error: Index out of range - python

seq_sum = []
for i in range(len(sequence)):
seq_sum[i] = sequence[i] + inv_sequence[i]
print (seq_sum)
When I try to run this code it return an error: list assignment index out of range. How can I fix the problem?
sequence and inv_sequence are arrays of integers.

seq_sum[i] will raise an IndexError as the seq_sum list is empty. You should use append instead:
seq_sum = []
for i in range(len(sequence)):
seq_sum.append(sequence[i] + inv_sequence[i])
print(seq_sum)
You can achieve the same result with a prettier code using list comprehension:
seq_sum = [seq_elem + inv_elem for seq_elem, inv_elem in zip(sequence, inv_sequence)]
You could also use map but some would argue its readability:
import operator
seq_sum = list(map(operator.add, sequence, inv_sequence))

You've declared seq_sum to be an empty list. You then try and index in a position other than 0 which results in an IndexError.
Expanding a list to make it larger is essentially done with appending, extending or slice assignments. Since you sequentially access elements, seq_num.append is the best way to go about this.
That is:
seq_sum[i] = sequence[i] + inv_sequence[i]
Should be instead changed to:
seq_sum.append(sequence[i] + inv_sequence[i])

Related

IndexError in function

def AddVct(Vct1,Vct2,VctLen):
Vct3 = []
n=1
while n < VctLen:
Vct3[n] = Vct1[n] + Vct2[n]
n += 1
print(Vct[n])
return Vct3
The program outputs:
IndexError: list assignment index out of range.
How to avoid this?
You can't assign to a list element that doesn't exist. And since you start with an empty list, no elements exist in it. Generally, you would append() instead.
Vct3.append(Vct1[n] + Vct2[n])
Or, you could initialize Vct3 to be the size you want beforehand:
Vct3 = [0] * VctLen + 1
Then the assignment you already have works fine.
Assuming you start with an empty list and use append(), list indices start at 0, so you should define Vct3 as a single-element list so that the indices match between the input and output lists.
Vct3 = [None] # or whatever you want the first value to be
Or else initialize n to 0 instead of 1 if you want to consider all the elements of the lists.
In that case, however, it would be more Pythonic to use a list comprehension
Vct3 = [a + b for (a, b) in zip(Vct1, Vct2)]
N. B. It's generally not necessary to pass in the length of a list as its own parameter. You can trivially get it using len().

function to add elements in list

I'm creating a program that adds the elements of the same cardinality in two separate lists:
list1 = [1,2,3]
list2 = [2,3,4]
Thus list3 would be [3,5,7]
This is the code I have:
def add_list(lst1,lst2):
sum_lst = []
index = 0
while (len(lst1)-1) >= index:
sum_lst[index] == lst1[index] + lst2[index]
index += 1
return sum_lst
I get this error "index out of range" when I run it:
sum_lst[index] == lst1[index] + lst2[index]
How is it out of range considering that I stop the index before it reaches past the length of the list?
sum_lst[index] == lst1[index] + lst2[index]
^1 ^2
2 main issues:
you initialize sum_lst as '[]` which means, YES, 0 IS out of index.
== is not the same as =. == is a boolean expression operation that asses equality whereas = is the assignment operator.
two fixes:
#replaces that one line
sum_lst.append(lst1[index]+lst2[index])
OR
#replaces the whole function
sum_lst = [x+y for x,y in zip(lst1,lst2)]
The reason you're running into your error message is because sum_lst doesn't yet have the indices you're looking for.
E.g. if you try
>>> some_list = []
>>> some_list[0] = 1 # you'll get
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
Instead, try something like:
sum_lst.append(lst1[index] + lst2[index])
This'll add a new element to the end of the array
The problem with this line was already pointed out:
sum_lst[index] == lst1[index] + lst2[index]
In addition to this fix, I'm going to explain a few steps you could take to improve this code and similar code.
Instead of incrementing an index and using a while loop, it's common practice to use a for loop in Python. We can use the range function to loop over all indexes.
Here's an improvement (note we fixed append and the == issue here):
def add_list(lst1, lst2):
sum_lst = []
for index in range(len(lst1)):
sum_lst.append(lst1[index] + lst2[index])
return sum_lst
But that still isn't idiomatic.
It would be even better to use the enumerate function to loop over items while retrieving their indices. Whenever you see something like for i in range(len(lst1)) think enumerate.
def add_list(lst1, lst2):
sum_lst = []
for index, item1 in enumerate(lst1):
sum_lst.append(item1 + lst2[index])
return sum_lst
The only reason we need the index is because we're trying to loop over two lists at once. Whenever you need to loop over multiple lists at the same time, you can use the zip function to zip iterables/lists together:
def add_list(lst1, lst2):
sum_lst = []
for item1, item2 in zip(lst1, lst2):
sum_lst.append(item1 + item2)
return sum_lst
This is nearly the best we could do. There's just one more improvement we could make: use a list comprehension instead of a for loop:
def add_list(lst1, lst2):
return [item1 + item2 for item1, item2 in zip(lst1, lst2)]
>>> [a+b for a,b in zip(list1,list2)]
[3, 5, 7]
I'd say the main problem with your code isn't the bug itself, it's that you're writing in a traditionally procedural pattern. Perhaps you used to do Java or C? Python is a multi-paradigm language, and supports functional programming. The main takeaway is that you should try to keep things immutable, so instead of creating empty lists and gradually populating them with content, try to create the resulting list on the fly. As in the example above. That way you won't be able produce indexing errors on either side of the assignment operator.
But, if you really want to know, your bug is two-fold:
>>> a = []
>>> a[1] = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
I.e. you can't append things to a list by assigning to a new element. You could do it this way instead:
a += [3]
Secondly you've used a comparison operator (==) instead of the assignment operator (=).

Facing an issue in removing duplicate entries in a list of my python Program

The below program is for entering the values to a list and print the list again after removing the duplicate entries... Can someone please have a look and let me know what would be the error in the program?
print ("Enter the Numbers into List \n")
list = []
n = int(input(""))
while n <= 1000:
list.append(n)
n = int(input(""))
m = len(list)
for i in range (0,m-1):
for j in range (i+1,m):
if list[i] == list[j]:
list.remove(j)
else:
pass
print (list)
When I run the program it gives below error:
File "python", line 23, in <module>
ValueError: list.remove(x): x not in list
There are several problems with your code.
The first is your assumption that list.remove() takes an index as its argument. It doesn't remove an element by index, but by value (see the method's documentation). The second is that if you modify a list as you iterate over it you may well find that this messes up your indexing:
>>> for i in range(len(lst)):
... if i == 2:
... del lst[i]
... else:
... print(lst[i])
...
1
2
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
IndexError: list index out of range
The third (minor) issue is that you are using the name of a built-in type (list) as a variable in your code, which will "shadow" the built-in type, making it inaccessible.
There are a number of problems in your solution:
The one you run into is that the remove method removes the first element that matches the argument, but you use the index of the element as argument which does not need to be one of the element. Instead if you want to remove an element by index you should use del mylist[index] instead.
Second you're trying to modify an list while iterating through it and that's not a good thing, you will probably not getting the result from that that you expect.
Also a aestetically questionable construct is calling your list list, that name is already used by the type list. By doing so you run into the problem that you can't use the builtin list anymore and that could be confusing.
The pythonic way to do this is to use the library functions and not reinventing the wheel (and of course not calling your list list):
import collections
mylist[:] = list(collections.OrderedDict.fromkeys(mylist).keys())
What it does is using OrderedDict which retains the order of the keys to put the element into and then create a list from that and then put it in the original list.
That solution however assumes that the items are hashable, which might not be the case. Otherwise the only solution is to iterate twice through the list as Cunningham's answer shows (which is therefore slower).
You are trying to remove j not what is in list[j], you also need to make a copy of the list and remove from that, when you remove elements you change the size of the list so apart from an index error you will try to remove elements that are not there:
m = len(lst)
out = lst[:]
for i in range(m - 1):
for j in range(i + 1, m-1):
if lst[i] == lst[j]:
out.remove(lst[j])
print(out)
To remove from the original list, you can use a set and reversed:
seen = set()
for ele in reversed(lst):
if ele in seen:
lst.remove(ele)
seen.add(ele)
print(lst)
Or use an OrderedDict:
from collections import OrderedDict
print(list(OrderedDict.fromkeys(lst).keys()))
A simple way using comprehension would be assuming your list name is l to avoid clashing with the type list:
l = [ l[i] for i in range(len(l)) if l[i] not in l[:i] ]
It avoids a name clash with the builtin type list, and modifying a list that you are iterating, and is still O(n2/2)
as you keep deleting the elements the length of list keeps decreasing and the index you are accessing might not be accessible
instead do something like
list(set(t))
and dont name your lists as the "list" keyword

Variation of suffix array in python

I'm relatively new to computer science, and I'm learning how to code in python. I'm trying to figure out how to make a function that takes a list and returns a list of suffixes from the inputted list, in order from shortest length to longest length. For example, entering
[3,4,2,-9,7,6,1]
to the function would return
[[],[1],[6,1],[7,6,1],[-9,7,6,1],[2,-9,7,6,1],[4,2,-9,7,6,1],[3,4,2,-9,7,6,1]]
I've tried several approaches, but so far I'm not having much luck. Here is what I have so far:
def h(m):
newlist = []
x = 0
y = (len[m])-1
while x in range(y):
sublist = []
sublist = sublist + m[x:y]
newlist.append(sublist)
x += 1
return new list
When I try to run the function by entering something like
a = [3,4,2,-9,7,6,1]
h(a)
I get an error:
Traceback (most recent call last):
File "<pyshell#239>", line 1, in <module>
h(a)
File "<pyshell#238>", line 4, in h
y = (len[m])-1
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
My objective with this bit of code was simply to create a the list of suffixes without sorting them by length. After I figure out how to create this new list I will add the sorting bit of the code. Keep in mind this is not a homework assignment. Any help would be greatly appreciated!
Possible solution is using list comprehension:
[l[i:] for i in range(len(l), -1, -1)]
This code uses slicing and list comprehension to simply return a list of slices from the end. Using your code, small modification is required - len is a function and not a dictionary, therefore you need to use the call operator () instead of subscript operator [].
y = len(m) - 1
That will not yield correct result though, because you will not get the last suffix and empty suffix. In order to cover these two, you will need to modify y or the loop to cover them
y = len(m) + 1
or better
while x in range(y + 1):
use parenthesis to get the length of the list:
y = len(m) - 1
Your error is in your len:
(len[m]) - 1
len is a function, and you can't index or slice or the what not. Do this instead:
y = len(m) - 1
There's also one other error:
return new list
Should be: (You can't have spaces in variables)
return newlist

ValueError while Merging Lists in Python

I'm trying to get one array out of several arrays in python 2.7
I found on the internet that this is done simply by adding both lists:
lista = [1,2,3]
listb = [3,4,5]
listc = lista + listb
In my case my first list i empty and the next list has 99 elements.
My code looks like this
data_complete = []
for i in range(1, numberOfFiles+1):
data = getDataFromFile(i)
data_complete = data_complete + data
The last line of code does not work, it returns the error:
data_complete = data_complete + data
ValueError: operands could not be broadcast together with shapes (0) (99)
I would be glad if someone can solve this.
Kind Regards
You can use append method if its a single item
data_complete.append (data)
You can use extend method if data itself is a list
data_complete.extend (data)
It looks like getDataFromFile is returning a numpy array, rather than a list. In this case, + will use the array's concatenation routine, which has some extra requirements compared to lists (and returns another array). You can use the list extend method instead to get around this:
data_complete = []
for i in range(1, numberOfFiles+1):
data = getDataFromFile(i)
data_complete.extend(data)
just append the data to your list
for example:
evens = []
for i in xrange(10):
if i%2 == 0:
evens.append(i)
at the end of this program evens will equal [2,4,6,8]

Categories

Resources