leo
leo

Reputation: 557

Pythonic way to filter list based on index

I am wondering whether there is a pythonic way to perform the following operation on python list. The input is : A large python list demo = [1,3,5,...], a input index list index like [0,1] or [2,3,5] etc. The intended output for demo = [1,3,5,6] with index like [0,1] will be [5,6] with values in the index list filtered out.

A method I can think of is : python list comprehension like [demo[i] for i in index] gives the opposite [1,3] and convert demo and [1,3] to set and apply set difference.

I am wondering better solution with better performance.

Upvotes: 0

Views: 757

Answers (1)

Adam Smith
Adam Smith

Reputation: 54213

demo = [1,3,5,7,9,11,13]
index = {2,3,5}
[value for i, value in enumerate(demo) if i not in index]
# [1, 3, 9, 13]
# Note that you can use a generator expression for a large list that you don't
#   require to be in memory all at once, e.g.
# (value for i,value in enumerate(demo) if i not in index)

You can also use filter

map(lambda x: x[1], filter(lambda x: x[0] not in index, enumerate(demo)))
# or map(operator.itemgetter(1), filter( ... ) )

Or even set operations, with some work....

correct_indexes = set(range(len(demo))) - index
[demo[i] for i in correct_indexes]

Upvotes: 4

Related Questions