Search code examples
pythonlistappendenumerate

enumerate append error while creating list from csv


I'm stuck in a process of creating list of columns. I tried to avoid using defaultdict.

Thanks for any help!

Here is my code:

# Read CSV file
with open('input.csv', 'r') as csvfile:
    reader = csv.reader(csvfile)
    #-----------#
    row_list = []
    column_list = []
    year = []
    suburb = []
    for each in reader:
        row_list = row_list + [each]
        year = year + [each[0]]#create list of years
        suburb = suburb + [each[2]]#create list of suburb
        for (i,v) in enumerate(each[3:-1]):
            column_list[i].append(v)
            #print i,v
    #print column_list[0]

My error message:

 19         suburb = suburb + [each[2]]#create list of suburb
 20         for i,v in enumerate(each[3:-1]):
 ---> 21             column_list[i].append(v)
 22             #print i,v
 23 #print column_list[0]

 IndexError: list index out of range

printed result of (i,v):

0 10027
1 14513
2 3896
3 23362
4 77966
5 5817
6 24699
7 9805
8 62692
9 33466
10 38792
0 0
1 122
2 0
3 
4 137
5 0
6 0
7 
8 
9 77
10 

Basically, I want to have lists to look like this.

column[0]=['10027','0']
column[1]=['14513','122']

A sample of my csv file:

enter image description here


Solution

  • Yes Like Alex mentioned the problem is indeed due to trying to access the index before creating/initializing it as an alternative solution you can also consider this.

    for (i,v) in enumerate(each[3:-1]):
                if len(column_list) < i+1:
                    column_list.append([])
                column_list[i].append(v)
    

    hope It may Help !