[SOLVED] Slicing Nested List

Issue

I’m familiar with slicing, I just can’t wrap my head around this, and I’ve tried changing some of the values to try and illustrate what’s going on, but it makes no sense to me.

Anyway, here’s the example:

l = [[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]]  
print l[:,0:2]

Resulting in:

[[0, 0], [0, 1] [1, 0], [1, 1]]

I’m trying to translate this as “slice from index 0 to 0,2, incrementing by 2” which makes no sense to me.

Solution

What you are doing is basically multi-axis slicing. Because l is a two dimensional list and you wish to slice the second dimension you use a comma to indicate the next dimension.

the , 0:2 selects the first two elements of the second dimension.

There’s a really nice explanation here. I remember it clarifying things well when I first learned about it.

Answered By – GWW

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *