NVaughan
NVaughan

Reputation: 1665

IndexError in Python3

I have the following MWE:

def get_files():
    file_list = ['first', 'second', 'third', 'fourth']
    return file_list

def set_names(orig_flist):
    file_list = []
    for i in range(len(orig_flist)):
        file_list[i] = orig_flist[i]
    return file_list

set_names(get_files())

When I run it, I get this error:

Traceback (most recent call last):
  File "privpub.py", line 11, in <module>
    set_names(get_files())
  File "privpub.py", line 8, in set_names
    file_list[i] = orig_flist[i]
IndexError: list assignment index out of range

I don't understand what's going on. Can somebody explain me, please?

Upvotes: 2

Views: 94

Answers (1)

Will
Will

Reputation: 4469

You are trying to assign a value to an index in the list that does not exist yet:

file_list = []
for i in range(len(orig_flist)):
    file_list[i] = orig_flist[i]

You will want to use append in order to lengthen your list like so:

file_list = []
for i in range(len(orig_flist)):
    file_list.append(orig_flist[i])

Upvotes: 3

Related Questions