ashish karan ashish karan - 6 months ago 7
Python Question

Why is this python list showing empty in this certain case?

I am trying to open a text file using the csv module in which i have some values that is then extracted and two seperate lists are populated.

This is the example.txt file:

1,2
3,4
6,8
8,2
9,3


There are different outputs in different scenarios when i try to run this code:

with (open('A:\WorkSpace--Python\Plotter\MainSource\example.txt','r')) as egFile:
plot=csv.reader(egFile,delimiter=',')
x=[int(row[0]) for row in plots]
y=[int(row[1]) for row in plots]


In ipython, when i reference x and y it outputs empty list for y.

For x:


[1, 3, 6, 8, 9]


For y:


[]


But if i comment out the line where x is being populated, then referencing y returns the appropriate list.

with (open('A:\WorkSpace--Python\Plotter\MainSource\example.txt','r')) as egFile:
plot=csv.reader(egFile,delimiter=',')
'''x=[int(row[0]) for row in plots]'''
y=[int(row[1]) for row in plots]


Output y:


[2,4,8,2,3]


I have tried using different variable names , but the result remains same.

Answer

A csv.reader is a lazy (meaning it only produces data as needed) iterator that gets exhausted when you iterate through it once, like a generator. After declaring x it is empty.

You can materialise it with list to allow multiple iterations:

plot = list(plot)

However if your CSV file is large this will take a lot of memory, although it doesn't really make a difference in this case since you're saving all the values in x and y anyway.

An alternative would be:

x = []
y = []
for row in plot:
    x.append(int(row[0]))
    y.append(int(row[1]))

or

x = []
y = []
for xrow, yrow in plot:
    x.append(int(xrow))
    y.append(int(yrow))
Comments