Checking the next object in Python list
<p>I have a <code>list</code> (from CSV) with the following information structure:</p>

<pre><code>Item 1
NUMBER Random ID
Item 2
NUMBER Random ID
Item 3
Item 4
Item 5
NUMBER Random ID
</code></pre>

<p>And I would like to create a new <code>list</code> (CSV) that looks like this:</p>

<pre><code>Item 1 NUMBER Random ID
Item 2 NUMBER Random ID
Item 5 NUMBER Random ID
</code></pre>

<p>So I would like to create a string from <code>Item 1,2,3...</code> and the line under it, if the next line doesn't contain the string <code>NUMBER</code>. </p>

<p>I can read the CSV and use it as a list, however I don't know how the track the lines. My first idea is to create a list of dicts where every dict contains the index number of the line and the content, and then I can loop through the <code>list_with_dicts</code> and check the next line from the original list.</p>

<pre><code>raw_list = [] 
num = 0
list_with_dicts = []
for x in raw_list:

    num2 = num + 1
    dict1 = {}
    dict1['index'] = num2
    dict1['Ã§ontent'] = x 
    list_with_dicts.append(dict1)

for d in list_with_dicts:

    number_of_next_line = d['index'] + 1    

    if "NUMBER" in raw_list[number_of_next_line]:
        new_string = "%s %s" % (d[content], raw_list[number_of_next_line])
    else:
        print("String without number")
</code></pre>

<p>However I'm not sure that it's the easiest and best way to do it, so I would really appreciate if somebody could show me a simpler workaround if it's possible.</p>

<p>Here's a slightly different take on the problem - search for lines that contain the string <code>NUMBER</code> and then join that line with the previous one. This produces simpler code:</p>

<pre><code>l = ['Item 1', 'NUMBER Random ID', 'Item 2', 'NUMBER Random ID', 'Item 3', 'Item 4', 'Item 5', 'NUMBER Random ID']

result = []
for i, s in enumerate(l[1:], 1):
    if 'NUMBER' in s:
       result.append('{} {}'.format(l[i-1], s))
</code></pre>

<p>Or as a list comprehension:</p>

<pre><code>result = ['{} {}'.format(l[i-1], s) for i,s in enumerate(l[1:], 1) if 'NUMBER' in s]
</code></pre>

<p>It's unclear what is expected as output - you mention CSV which implies that the output list should contain individual fields, in which case the result should be a list of lists. Something like this:</p>

<pre><code>result = [[l[i-1], s] for i,s in enumerate(l[1:], 1) if 'NUMBER' in s]
</code></pre>

<p>which would create this list of lists:</p>

<pre><code>[['Item 1', 'NUMBER Random ID'],
 ['Item 2', 'NUMBER Random ID'],
 ['Item 5', 'NUMBER Random ID']]
</code></pre>

<p>which can easily be saved to a CSV file with the <code>csv</code> module:</p>

<pre><code>import csv

with open('result.csv', 'w') as f:
    csv.writer(f).writerows(result)
</code></pre>

python