'Splitting large list into chunks using modulos [duplicate]

I'm wondering why the simple code below doesn't work:

my_list = range(0, 6)

num_proc = 3

chunks = [[]] * num_proc

i = 0
for item in my_list:
    idx = i % num_proc
    i += 1
    chunks[idx].append(item)

print(f"Chunked items = {chunks}")

It outputs:

Chunked items = [[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]

The output I expect is

Chunked items = [[0, 3], [1, 4], [2, 5]]

Seems that the problem lies with statement

 chunks[idx].append(item)

Yet, I'm at a loss on how to fix that



Solution 1:[1]

This is happening because [[]] * num_proc creates a reference of the same list num_proc times so any change to one them updates all of them.

So instead of:

chunks = [[]] * num_proc

Do:

chunks = [[] for _ in range(num_proc)]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1