[Tutor] help with slice
alan.gauld at btinternet.com
Wed Mar 5 01:24:45 CET 2008
"washakie" <washakie at gmail.com> wrote
> Could someone please explain 'slices' also for dictionaries?
So far as I know slices don;t work for dictionaries directly -
don't have the concept of order. However you could get a list of
keys and apply a slice to that, although I'm not sure how it
would ever be useful.
> basically, I'd like to know how you would call every 3rd element in
> a list
> of lists...
> My logic says: ThirdElems=List[:]
> Which to me reads, for every item in List (which are lists), return
> third item.but this doesn't work.
This actually says take a copy of the list and give me
the 3rd element of that copy.
You need to use a list comprehension:
thirds = [sublist for sublist in myList]
Author of the Learn to Program web site
More information about the Tutor