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]])
Firebase Cloud Functions: PubSub, "res.on is not a function"
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
The goal is to overcome the problem of slow execution of nested loops in python by using the built-in functions in numpy
I used a function to collect some links of a website, which lead to pdf filesThese pdf files I want to download in a seconde step
I am trying to use the pyimage module for Python using Jupyter notebooks (or alternatively PyDev in Eclipse)I managed, after many failed attempts, to make it run but only partially in Jupyter