Rishabh
Rishabh

Reputation: 900

Python - list assignment index out of range when trying to assign value to list item within loop

I am trying to assign (or replace) items within a list inside two nested for loops. Below is the code (base_list is already defined, so the code might look incomplete):

list_init = 'test'
# converting new list to type list
new_list = list(list_init)
flag = [0]
for i in range(len(base_list)):
    for j in range(i, len(base_list)):

        if base_list[i] == base_list[j]:
            print(base_list[j],' is equals to', base_list[i])
            # below is the error line
            new_list[j] = base_list[j]
            flag[j] = 1
        else:
            print(base_list[j],' is not equals to', base_list[i])
            # below is the error line
            new_list[j] = base_list[j]
            flag[j] = 0

What I am doing is to iterate over same list (base_list) twice to compare each element of the list with each other element after that element, and whenever a match is found, I am assigning the first base_list value to new_list for each match. When match is not found, I am assigning current base_list value as it is to new list. Therefore I am taking second loop as:

for j in range(i, len(base_list))

This is to make sure that second loop starts from the list item active in first loop, and does not iterate from beginning.

Now the problem is in the following line:

new_list[j] = base_list[j]

I am getting the following error:

new_pl[j] = pl_list[i]
IndexError: list assignment index out of range

The same kind of problem I am facing with the flag list:

flag[j] = 1

Can you please suggest any solution to assign (or replace) list element values within loops using indices?

Upvotes: 1

Views: 120

Answers (1)

dursk
dursk

Reputation: 4445

The issue is with the way you are initializing new_list, in this line:

new_list = list(list_init)

Your list_init is set to 'test', so when you create new_list, it looks like

['t', 'e', 's', 't']

Then, if the length of base_list is > 4, you are trying to assign an element to new_list at index 5 for example, and getting an IndexError.

You should create new_list like so:

new_list = [None] * len(base_list)

This way you can ensure that new_list has the same length as base_list and you won't get any IndexErrors. Same thing for flag.

Upvotes: 2

Related Questions