Need Help Slicing & Indexing Nested List with Python

Solution for Need Help Slicing & Indexing Nested List with Python
is Given Below:

Haven’t used Python in a few months and I’m struggling to figure out how I can slice & index nested lists.

So, I was reading Scikit-Learn’s Getting Started Documentation. I’ll use their code in this post for a better interpretation of what I’m trying to do.

Our Sample Matrix (“Nested List”)

X = [[ 1,  2,  3],  # 2 samples, 3 features
     [11, 12, 13]]

I’m looking to return a list containing every sample’s first feature.

[1, 2, 3]

*Confused* That’s not what I expected. Even weirder… Switching the index values around returned the same thing.

[1, 2, 3]

What the heck am I doing wrong here?

Assuming you expected [1, 11], I think you’re thinking of NumPy array slicing.

import numpy as np

a = np.array(X)
print(a[:,0])  # -> [ 1 11]

In plain Python, there’s no way to do it without looping, for example:

print([x[0] for x in X])  # -> [1, 11]

Using [:] on a list just makes a copy of it.