-3

input: L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

How to concatenate every 4th occurrence in a list using for loop.

Explanation1: [0+4+8,1+5+9,2+6+10,3+7+11] like this and my final out put should be

Output: [12,15,18,21]

1 Answers1

3

You can just use slicing, which takes a step:

>>> L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> [sum(L[i::4]) for i in range(0,4)]
[12, 15, 18, 21]

A terminology note, you aren't concatenating, here you are summing. Concatenate means to join two sequences (e.g. a string, or a list, or a tuple). Although, in Python, the + operator is used for concatenating sequences, in this case, you are using the + operator on numbers, so it is addition, not concatenation.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172