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>With <code>enumerate(&lt;list&gt;)</code> you can iterate on indices and elements, so you can easily check the next element:</p>

<pre><code>result = []
for i, val in enumerate(lst):
    if i == len(lst) - 1:
        break # to avoid IndexError
    if lst[i + 1][:3] == 'NUM':
        result.append('%s %s' % (val, lst[i + 1])
</code></pre>

<p>Version with functional programming:</p>

<pre><code>result = \
    list(
        map(
            lambda i: 
                 '%s %s' % (lst[i - 1], lst[i]),
            filter(
                lambda i:
                    lst[i][:3] == 'NUM',
                range(1, len(lst))
            )
        )
    )
</code></pre>

python