Extracting an undefined number of items from a list

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Apr 13 04:26:52 CEST 2010

On Mon, 12 Apr 2010 13:05:30 -0700, vsoler wrote:

> Hi everyone,
> say that 'db' is a list of values
> say 'i' is a list of indexes
> I'd like to get a list where each item is i-th element of db.
> For example:
> db=[10,20,30,40,50,60,70,80,90]      #undefined length 
> i=[3,5,7]  #undefined length then 
> result=[30,50,70]  # resulting list
> how can I do this?

Others have given a simple solution using list comprehensions. Here's 
another few ways.

# The beginner's way
result = []
for index in i: # "i" is a bad name for a list of indexes
    x = db[index - 1]  # shift from one-based counts to zero-based

# The advanced functional way
from operator import itemgetter
indexes = map(lambda n: n-1, i)  # adjust for one-based counts
result = itemgetter(*indexes)(db)

# The obfuscated, fragile way
map( itemgetter(0), sorted(
     zip(db, range(1, len(db)+1)), key=lambda t: t[1] if t[1] in i else -1
     )[-len(i):] )


More information about the Python-list mailing list