slice lists

Robert Kern rkern at ucsd.edu
Mon Sep 19 16:19:40 EDT 2005


jbperez808 at yahoo.com wrote:
> Reading:
> 
>   http://docs.python.org/ref/slicings.html
> 
> it would seem to indicate that the ff will work:
> 
>   L=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> 
> however, you get:
> 
>   >>> l[3:4:,5:8:]
>   Traceback (most recent call last):
>     File "<pyshell#153>", line 1, in ?
>       l[3:4:,5:8:]
>   TypeError: list indices must be integers
> 
> in Python 2.3...  are they only available in 2.4?

Lists are one-dimensional. They can only take one slice, not two.

> Also,
> 
>   http://www.python.org/doc/2.3/whatsnew/section-slices.html
> 
> mentions that:
> 
>   "Ever since Python 1.4, the slicing syntax
>   has supported an optional third 'step' or 'stride'
>   argument. For example, these are all legal Python syntax:
>   L[1:10:2], L[:-1:1], L[::-1]."
> 
> and yet, we see in:
> 
>   http://pyds.muensterland.org/weblog/2004/12/25.html
> 
> that something as simple as:
> 
>   l = range(0,10)
>   print l[1:5]     # this works
>   print l[1:5:2]   # this barfs 
> 
> fails in Python 2.2.  What gives?

The syntax was there since 1.4 for the Numeric module[1], but the list
object itself wasn't updated to utilize that syntax until later.

[1] http://numeric.scipy.org

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter




More information about the Python-list mailing list