Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #43859 > unrolled thread

Re: Strange behavior for a 2D list

Started byPeter Otten <__peter__@web.de>
First post2013-04-18 23:12 +0200
Last post2013-04-18 23:12 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Strange behavior for a 2D list Peter Otten <__peter__@web.de> - 2013-04-18 23:12 +0200

#43859 — Re: Strange behavior for a 2D list

FromPeter Otten <__peter__@web.de>
Date2013-04-18 23:12 +0200
SubjectRe: Strange behavior for a 2D list
Message-ID<mailman.795.1366319582.3114.python-list@python.org>
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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web