# Do structural, historical or philosophical reason(s) explain why native python allow slicing list of lists only with list comprehension? [closed]

93
December 13, 2019, at 09:40 AM
Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 14 hours ago.

Why native python doesn't allow calling a full or a slice of list of lists

``````table=[list(range(10)),list(range(10)),list(range(10))]
#calling the first column
a=table[:][0]
#calling a subset of table
b=table[0:2][1:4]
``````

instead of the heavy and overcomplicated list comprehension approach?

``````a = [row[0] for row in table]
b = [row[1:4] for row in table[0:2]]
``````

Whereas we can call `c=table[1][0:3]`, why can't python allowed calling for `table[0:2][0:3]` with ease? Is there a structural, an historical or a philosophical reason to allow such slicing using only list comprehension?

Using a list comprehension is the straightforward way.

`table[0:2][1:4]` doesn't do what you want because `table[0:2]` is a list of the first two elements of `table`, so `[1:4]` takes a slice of that list which still just contains elements of `table`. Both are slice operations on two-dimensional lists, so there is no semantic reason that one slice should return some unchanged rows while the other slice should return all rows but with only some of the columns.

The reason Python does not include such an operation on the built-in list type is probably that the comprehensions are easy enough to write, simple enough to read to understand their meaning, and the need for multi-dimensional slicing of native lists is not that common.

Note also that these are two different kinds of "multi-dimensional slice" - one returns a single column as a one-dimensional list the other returns a new two-dimensional list. Whether you want a sliced column to be one- or two-dimensional will depend on the use-case, and if the built-in `list` class took a stance on which one is "correct" then it could easily lead to problems for some users who expect the other behaviour.

If you need multi-dimensional matrices of elements, the numpy package supports a clean syntax for multi-dimensional slicing. You may already be using it for multi-dimensional data anyway, and if you're not then you should consider it.

``````>>> import numpy
>>> m = numpy.array([list(range(10)), list(range(10)), list(range(10))])
>>> m[:, 0]
array([0, 0, 0])
>>> m[0:2, 1:4]
array([[1, 2, 3],
[1, 2, 3]])
``````
POPULAR ONLINE

### How to speed up the loop over an OpenCV image in Python using Numpy?

The goal is to overcome the problem of slow execution of nested loops in python by using the built-in functions in numpy

149

### Load Excel file into database as varbinary using python

I have Output1xlsx and Output2

101