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])]
You can explicitly create an iterable with the
iter()
builtin, then call `next(iterable) to consume one item. Final result is something like this: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.
When you call
, the pairs that it generates are not
, but rather
That is, the start value indicates what the first index used should be, not what the first element to use is.
Perhaps an alternate way of doing this would be as follows:
There is not much merit here for using enumerate() ... you can simply
.pop()
the n-th item from inner lists. For loop over your data, starting at index 1 and add the 2nd value (popped) to the 1st element of the inner list:Output:
See list.pop(index)