0

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.

3 Answers 3

5

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]
Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.