As you found out there's no way to slice a collections.deque. But it supports rotation which could be used in this case:
last_n = 10
my_deque.rotate(last_n)
for i in itertools.islice(my_deque, last_n):
pass
The problem with itertools.islice in this case is that it needs to iterate over all elements until it reaches the stop. That's because it needs to work with iterators in general not only with random-access-containers like lists and deques. So in your case the islice really had to iterate over all elements in the deque. With rotate and then islice it only has to iterate over 10 elements.
As for timings, it's hard to know what you compared but using this setup:
from collections import deque
import itertools
my_deque = deque(range(10000))
my_list = list(range(10000))
I get the following timings:
%%timeit
my_deque.rotate(10)
for i in itertools.islice(my_deque, 10):
pass
my_deque.rotate(-10) # so the next timing operates on the orginal deque again
2.76 µs ± 41.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%%timeit
start = max(0, len(my_deque) - 10)
for i in itertools.islice(my_deque, start, None):
pass
136 µs ± 8.08 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%%timeit
start = max(0, len(my_list) - 10)
for i in itertools.islice(my_list, start, None):
pass
119 µs ± 1.64 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit my_list[-10:]
434 ns ± 12.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
So it can't beat list slicing (still ~5 times slower) but it's definitely much faster (~50 times) than using your islice approaches.
timeitresults. - John Zwinckitertoolsis designed for working with arbitrary, possibly infinite, iterators. An infinite iterator doesn't have a "last" 10 items. Also, for an arbitrary iterator, the only way to get an item is to call itsnextmethod to get a single item; more efficient methods simply don't exist. - chepnerfor i in list(itertools.islice(my_deque, start, None)):the conversion into a list is useless and may use memory for nothing. - glenfantdeque.rotate()then yield values till your desired range ? - Chiheb Nexus__reversed__method, only some containers have that method. - MSeifert