Skip to content
Advertisement

how to get nth chunks of items of a list in python?

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:

l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']

four_chunks = [l[x:x+4] for x in range(0, len(l), 4)]

##output of four_chunks: 
[['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]


Desired output:

[['a', 'b', 'c', 'd'], ['d', 'e', 'f', 'g'], ['g', 'h', 'i', 'j']]

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.

four_chunks = [l[x:x+4] for x in range(0, len(l), 3)]
# or
four_chunks = [l[x:x+4] for x in range(0, len(l) - 3, 3)]

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement