Dhruvil21_04
Dhruvil21_04

Reputation: 2189

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

Upvotes: 3

Views: 5206

Answers (3)

marek.s
marek.s

Reputation: 11

You need to append an item to the list. It would look like that then:

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

Since when you created an empty list, it had no items, thus accessing it via index didn't work. You can also skip the while loop and use some Python sugar to get the same effect:

file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl']
path = ['D:\\Work\\' + x + '.csv' for x in file_name]
for p in path:
    print(p)

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

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)

Upvotes: 4

Sagun Shrestha
Sagun Shrestha

Reputation: 1198

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.

Upvotes: 1

Related Questions