clwen
clwen

Reputation: 20889

Better ways to get nth element from an unsubscriptable iterable

Sometimes an iterable might be not subscriptable. Say the return from itertools.permutations:

ps = permutations(range(10), 10)
print ps[1000]

Python will complain that 'itertools.permutations' object is not subscriptable

Of course one can perform next() by n times to get the nth element. Just wondering are there better ways to do so?

Upvotes: 20

Views: 5666

Answers (2)

lovasoa
lovasoa

Reputation: 6855

A more readable solution is :

next(x for i,x in enumerate(ps) if i==1000)

Upvotes: 4

jamylak
jamylak

Reputation: 133514

Just use nth recipe from itertools

>>> from itertools import permutations, islice
>>> def nth(iterable, n, default=None):
        "Returns the nth item or a default value"
        return next(islice(iterable, n, None), default)

>>> print nth(permutations(range(10), 10), 1000)
(0, 1, 2, 4, 6, 5, 8, 9, 3, 7)

Upvotes: 32

Related Questions