[Tutor] extracting elements in a sequence

Alfred Milgrom fredm@smartypantsco.com
Sun Feb 9 17:11:03 2003


Hi Tim:

As far as I know there is no built-in way to extract the nth element out of 
a list, but it is very simple to write a function to do this for you:

def extract (oldlist, spacing):
     count = 0
     newlist = []
     for item in oldlist:
         if count % spacing == 0:
             newlist.append(item)
         count = count+1
     return newlist

oldlist = [1,'one',2,'two',3,'three']
newlist = extract(oldlist, 2)
print newlist
newlist = extract(oldlist, 3)
print newlist

(The % operator is the modulo function)

Hope this helps you,
Alfred Milgrom