It's pretty simple actually. Just follow through the values of the two loops:
Starting with the outer loop, r
would be 0
, then 1
, then 2
, etc. Let's look at the case for which r == 1
. When running through the different values of i
, (which would be 0, 1, 2, ... len(lst)
, the value of i % 4
, meaning the remainder of dividing i
by 4
, would be 0, 1, 2, 3, 0, 1, 2, 3, ...
. So the i % 4
would be equal to r
, for every 4 values of i
!
For our chosen r == 1
, that would mean we're choosing lst[1], lst[5], lst[9], ...
, etc.
And for r == 2
? You guessed it! You'd be picking up lst[2], lst[6], lst[10],...
.
So over all you'd get 4 lists, with non-overlapping elements of the original list, by just "jumping" 4 elements every time, but starting at different values.
Which naturally leads to the more simple solution:
def even_divide(lst, num_piece=4):
return [lst[r::num_piece] for r in range(num_piece)]