AAZA
AAZA

Reputation: 1

2-D Array Slicing without NumPy Import

I'm learning how to work through 2-D arrays and am currently trying to figure out how to do this without the numPy import. A simple 1-D array could be sliced accordingly:

Array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Array[start:stop:step]

But what if the array were to be instead:

Array2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I see that I can slice certain elements contained in the lists of the list like:

Array2[0][1]
2

However, what would be a possible method of slicing say elements 3, 4, 5, 6, 7, 9 (or whichever values) while they are still contained in their respective lists.

Upvotes: 0

Views: 998

Answers (1)

user9105277
user9105277

Reputation:

There's no easy way to index nested lists the way that you want. However, you can achieve the effect of flattening the list (returning a single list, we'll call Array3) then indexing appropriately.

Array2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Array3 = [item for sublist in Array2 for item in sublist]
Array3[2:]
>>>> [3, 4, 5, 6, 7, 8, 9]

For more info, see How to make a flat list out of list of lists?

Upvotes: 1

Related Questions