Appending to a list from a for loop (to read a text file)
<p>How do I append to an undetermined list from a for loop?
The purpose is to first slice each line by '-'. Then I would like to append these slices to an array without a determined size. I have the following code, and am loosing hair because of how simple this seems! </p>

<p>Each line in the text file looks like the following: 
2014-06-13,42.7,-73.8,27</p>

<p>program so far:</p>

<pre><code>f = open('Lightning.txt')

lightning =list()

for templine in f:

    if not templine.startswith('2014'): continue

    templine = templine.rstrip('-')

    line = templine.split()

    print line[2]
</code></pre>

<p>Thank you community,</p>

<p>This is an ideal job for the <a href="https://docs.python.org/2/library/csv.html#csv.reader" rel="nofollow">csv</a> lib:</p>

<pre><code>import csv

with open('Lightning.txt') as f:
    data = []
    # unpack the elements from each line/row
    for dte, _, _, i in csv.reader(f):
        # if the date starts with 2014, add the date string and the last element i
        if dte.startswith('2014'):
            data.append((dte, i))
</code></pre>

<p>Which can all be done using a list comp:</p>

<pre><code>import csv

with open('Lightning.txt') as f:
    data = [(dte, i) for dte, _, _, i in csv.reader(f) if dte.startswith('2014')]
</code></pre>

python string list append slice