Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better ways to get nth element from an unsubscriptable iterable

Tags:

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?

like image 820
clwen Avatar asked Aug 17 '12 14:08

clwen


2 Answers

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)
like image 183
jamylak Avatar answered Sep 19 '22 07:09

jamylak


A more readable solution is :

next(x for i,x in enumerate(ps) if i==1000)
like image 27
lovasoa Avatar answered Sep 20 '22 07:09

lovasoa