[GIS] Store in a python list the attribute table of a vector in QGIS

pyqgispythonqgis

I'm stuck with a very simple issue..
I've loaded in QGIS (through the py console) a csv layer (no geometry) made of 4 fields and 3 rows:

#load the csv
layer = QgsVectorLayer("path/to/the/csv", "csvlayer", "delimitedtext")
#add it to the TOC
QgsMapLayerRegistry.instance().addMapLayer(layer)

What I'm trying to do is to store the attribute table of the csv layer in a python list. I tried:

for i in layer.getFeatures():
    l = []
    l.append(i.attributes())

it works, but in the list I have only the last row of the attribute table and not all the 3 rows.

How can I have store all the 3 rows as lists in the main list?

Something like:

l
[[1,2,3], [4,5,6], [7,8,9]]

Best Answer

It is a pure Python question: in your script you initialize the list at each iteration

t = [1,2,3,4]
for i in t:
    l = []
    l.append(i)

 print l 
 [4]

while

 l = []
 for i in t:
     l.append(i)

 print l 
 [1,2,3,4]

or with list comprehensions

l = [i for i in t]

So, your script becomes:

l = [i.attributes() for i in layer.getFeatures()]
Related Question