I'm impressed by and enjoy the fact that a simple Python for
statement can easily unravel a list of lists, without the need for numpy.unravel
or an equivalent flatten function. However, the trade-off is now that I can't access elements of a list like this:
for a,b,c in [[5],[6],[7]]:
print(str(a),str(b),str(c))
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 1)
and instead, this works, up until the length-1 [5]
:
for a,b,c in [[1,2,3],[4,5,6],[7,8,9],[0,0,0], [5]]:
print(a,b,c)
1 2 3
4 5 6
7 8 9
0 0 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 1)
Logically, it doesn't make sense to assume that a list would have a fixed number of elements. How come then, Python allows us to assume that a list of lists would always have the same number of elements?
I'd like to be aware of what Python expects, because I want to anticipate wrongly formatted lists/sublists.
I've poked around Python documentation and Stackoverflow, but haven't found the reasoning or how the interpreter is doing this.
My guess is that flattening same-length arrays is such a common occurrence (e.g. machine learning dimensionality reduction, matrix transformations, etc.), that there's utility in providing this feature at the trade-off of being unable to do what I've tried above.