Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve IndexError: list assignment index out of range using array inside loop in Python

I'm new to python. I'm creating 2 arrays file_name(stores name of the files) and path(stores paths of files). Values of path array are assigned inside while loop. But I'm getting the error:

IndexError: list assignment index out of range in Python

I had already wasted several hours on this one, but haven't got the output as I expected. So, can you please let me know where I have made the mess? Any help will be highly appreciated. Thanks in advance.

My Code:

file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl']
path = []

count = 0
while count < 9:
    path[count] = "D:\\Work\\"+file_name[count]+".csv"
    print (path[count])
    count = count + 1

Expected Output:

D:\\Work\\abc.csv
D:\\Work\\xyz.csv
D:\\Work\\pqr.csv
D:\\Work\\mno.csv
D:\\Work\\def.csv
D:\\Work\\ghi.csv
D:\\Work\\rst.csv
D:\\Work\\uvw.csv
D:\\Work\\jkl.csv
like image 742
Dhruvil21_04 Avatar asked Feb 26 '26 08:02

Dhruvil21_04


2 Answers

You can't access path[count] and assign something to it if path[count] doesn't already exist.

To create a new list, use .append(). You don't need to keep track of a counter at all (it's rarely necessary to do a C-style loop in Python; the pythonic way is to iterate over the elements of a list/tuple/dictionary directly):

file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl']
path = []

for item in file_name:
    newpath = "D:\\Work\\" + item + ".csv"
    # or better: newpath = r"D:\Work\{}.csv".format(item)
    path.append(newpath)
    print(newpath)
like image 184
Tim Pietzcker Avatar answered Mar 01 '26 13:03

Tim Pietzcker


You are looking for the append method.

file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl']
path = []

count = 0
while count < 9:
    path.append("D:\\Work\\"+file_name[count]+".csv")
    print (path[count])
    count = count + 1

You will get your expected output.

like image 26
Sagun Shrestha Avatar answered Mar 01 '26 12:03

Sagun Shrestha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!