Search code examples
pythonenumerate

Enumerate list of elements starting from the second element


I have this list

[['a', 'a', 'a', 'a'],
 ['b', 'b', 'b', 'b', 'b'],
 ['c', 'c', 'c', 'c', 'c']]

and I want to concatenate 2nd and 3rd elements in each row, starting from the second row, to make something like this:

[['a', 'a', 'a', 'a'],
 ['b', 'bb', 'b', 'b'],
 ['c', 'cc', 'c', 'c']]

It seems to work fine, when I do it to every row:

for index, item in enumerate(list_of_lines, start=0):
    list_of_lines[index][1:3] = [''.join(item[1:3])] 

but when I'm starting from the second row - I have "list index out of range" error:

for index, item in enumerate(list_of_lines, start=1):
    list_of_lines[index][1:3] = [''.join(item[1:3])] 

Solution

  • You can explicitly create an iterable with the iter() builtin, then call `next(iterable) to consume one item. Final result is something like this:

    line_iter = iter(list_of_lines[:])
    # consume first item from iterable
    next(line_iter)
    for index, item in enumerate(line_iter, start=1):
        list_of_lines[index][1:3] = [''.join(item[1:3])]
    

    Note the slice on the first line, in general it's a bad idea to mutate the thing you're iterating over, so the slice just clones the list before constructing the iterator, so the original list_of_lines can be safely mutated.