Strange behavior for a 2D list

Peter Otten __peter__ at web.de
Thu Apr 18 17:12:52 EDT 2013


Robrecht W. Uyttenhove wrote:

> Hello,
> 
> I tried out the following code:
> y=[range(0,7),range(7,14),range(14,21),range(21,28),range(28,35)]
>>>> y
> [[0, 1, 2, 3, 4, 5, 6],
>  [7, 8, 9, 10, 11, 12, 13],
>  [14, 15, 16, 17, 18, 19, 20],
>  [21, 22, 23, 24, 25, 26, 27],
>  [28, 29, 30, 31, 32, 33, 34]]
> 
>>>> y[1:5:2][::3]
> [[7, 8, 9, 10, 11, 12, 13]]
> 
> I expected the 2D list:
> [[ 7, 10, 13],
>  [21, 24, 27]]
> 
> Any ideas?

It is not really a 2D list; rather a list of lists. You cannot see the two 
slices together, the slicing happens in two separate steps.

y[1:5:2] is a list containing two items (that happen to be lists)

>>> x = y[1:5:2]
>>> x
[[7, 8, 9, 10, 11, 12, 13], [21, 22, 23, 24, 25, 26, 27]]

x[::3] then operates on the outer list

>>> x[::3]
[[7, 8, 9, 10, 11, 12, 13]]

By the way, numpy offers the behaviour you expected:

>>> import numpy
>>> a = numpy.array(y)
>>> a
array([[ 0,  1,  2,  3,  4,  5,  6],
       [ 7,  8,  9, 10, 11, 12, 13],
       [14, 15, 16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25, 26, 27],
       [28, 29, 30, 31, 32, 33, 34]])
>>> a[1:5:2,::3]
array([[ 7, 10, 13],
       [21, 24, 27]])

Note that both slices are passed in the same a[...] operation.




More information about the Python-list mailing list