user1700890
user1700890

Reputation: 7730

Python list of indicies in list

Here is my code

a = [10,11,12]
index = [0,2]
print(a[index])

I expect 10,12 as output, but get error:

TypeError: list indices must be integers, not list

Is is possible to achive something like this in python? I know I can do it with list comprehension, but want something simpler. The problem looks so pythonic.

Upvotes: 0

Views: 98

Answers (3)

thebjorn
thebjorn

Reputation: 27311

If you want special semantics, you can create a list subclass:

class PickList(list):
    def __getitem__(self, key):
        return PickList([super(PickList, self).__getitem__(k) for k in key])

a = PickList([10,11,12])
index = [0, 2]
print a[index]

Upvotes: 1

Alex Lisovoy
Alex Lisovoy

Reputation: 6065

You can use operator.itemgetter:

In [1]: from operator import itemgetter

In [2]: a = [10, 11, 12]

In [3]: index = [0, 2]

In [4]: itemgetter(*index)(a)
Out[4]: (10, 12)

Upvotes: 3

awesoon
awesoon

Reputation: 33661

What's wrong with list comprehensions?

In [1]: a = [10, 11, 12]

In [2]: indices = [0, 2]

In [3]: [a[i] for i in indices]
Out[3]: [10, 12]

Upvotes: 5

Related Questions