Supertech
Supertech

Reputation: 770

compact slice notation in Python 3

Is there a compact version of writing the following in Python 3:

print(columns[1],columns[8],columns[9])

Something like:

print(columns[1,8,9])

To get the same result.

Upvotes: 0

Views: 73

Answers (2)

chepner
chepner

Reputation: 531055

list.__getitem__ doesn't support any sort of "selection" syntax, though you can use operator.itemgetter to achieve something similar:

from operator import itemgetter

print(itemgetter(1,8,9)(columns))

That said, a class could define __getitem__ to support something similar. For example,

import operator


class ProjectionList(list):
    def __getitem__(self, index):
        if isinstance(index, tuple):
            return operator.itemgetter(*index)(self)
        else:
            return super().__getitem__(index)

Then

>>> z = ProjectionList([1,2,3])
>>> z[0]
1
>>> z[0,2]
(1, 3)

Upvotes: 3

Rahul Goel
Rahul Goel

Reputation: 880

Try this :-

from operator import itemgetter
print(*itemgetter(1, 8, 9)(columns))

Upvotes: 1

Related Questions