[Tutor] help with slice

Ole Henning Jensen tjampman at gmail.com
Wed Mar 5 00:24:12 CET 2008

> Could someone please explain 'slices' also for dictionaries?
> basically, I'd like to know how you would call every 3rd element in a list
> of lists... 
> My logic says: ThirdElems=List[:][2]
What this does is, just assign the 3 value of List to the variable.
look at this way, step by step.

 >>> lst = range(10) # Generate a list
 >>> print lst[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> lst == lst[:]

## So lst[:] is really (sort of) just the same list

 >>> lst[:][2]

# So lst[:][ is basically the same as lst[2]

> Which to me reads, for every item in List (which are lists), return the
> third item.
> but this doesn't work.

What you need to do is loop all the way through your list and then only 
do something to every third element in the list

This is an example of a for loop, that prints out every 3 element:

 >>> lst = ["hello", "sweet", "world", "goodbye", "sweet", "world"]
 >>> for index in lst:
	if index % 3 == 0:
		print lst[index]

Best Regards
Ole H. Jensen

More information about the Tutor mailing list