I would like to get every 4 chunks of a list of items, where the first item has the index corresponding to 4-1, so a previous step. I am only able to get every 4 chunks, but I am stuck at getting every item of the list to start at a “previous step” or 4-1.
Should I loop through this differently?
Current code:
JavaScript
x
9
1
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']
2
3
four_chunks = [l[x:x+4] for x in range(0, len(l), 4)]
4
5
##output of four_chunks:
6
[['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
7
8
9
Desired output:
JavaScript
1
3
1
[['a', 'b', 'c', 'd'], ['d', 'e', 'f', 'g'], ['g', 'h', 'i', 'j']]
2
3
As you can see in the desired output, every chunk begins with an item that ended the previous chunk. E.g. item [1] starts with ‘d’ rather than ‘e’.
Advertisement
Answer
As Veedrac and guorui said, you need to pick 3 as step
parameter of range
.
JavaScript
1
4
1
four_chunks = [l[x:x+4] for x in range(0, len(l), 3)]
2
# or
3
four_chunks = [l[x:x+4] for x in range(0, len(l) - 3, 3)]
4
What’s the difference? In case your list cannot be split on equal chunks (so len(l) % 3 != 1
) The latter will cut last chunk, the former will have last chunk with size < 4