ashish karan ashish karan - 1 year ago 86
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:


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:
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:
'''x=[int(row[0]) for row in plots]'''
y=[int(row[1]) for row in plots]

Output y:


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

Answer Source

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 = []
y = []
for xrow, yrow in plot: