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:

JavaScript

Desired output:

JavaScript

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

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