Displaying multiple results in a list

Steve Holden sholden at holdenweb.com
Mon Dec 3 23:00:08 CET 2001


"Russell Briggs" <russb at jump.net> wrote in message
news:741f261e.0112031331.75c2e1c6 at posting.google.com...
> Wanted to know if there was a way to specify ranges in a list such as:
>
> newlist = ["1", "2", "3", "4", "5", "6"]
>
> print newlist[1..3]  #ie:  print newlist[1], newlist[2], newlist[3]
>
> Can something like this be done?
>
Yes, but be careful! The first element of a list is element 0, NOT element
1.

What you need is the so-called "slicing" notation, which creates a new list
from a set of consecutive elements. For example:

PythonWin 2.0 (#8, Mar  7 2001, 16:04:37) [MSC 32 bit (Intel)] on win32.
>>> newlist = ["1", "2", "3", "4", "5", "6"]
>>> newlist[0:2]
['1', '2']
>>> newlist[:2]
['1', '2']
>>> newlist[3:]
['4', '5', '6']
>>> newlist[-3:-1]
['4', '5']
>>> newlist[1:-1]
['2', '3', '4', '5']
>>>

Negative indices can be useful if you want elements relative to the end of
hte list rather than to the beginning. Play about a bit in the interactive
interpreter and you'll soon find this notation feels quite natural.

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list