Generally, when you want to iterate over a portion of a list in Python, the easiest thing to do is just slice the list.
# Iterate over everything except the first item in a list
#
items = [1,2,3,4]
iterrange = (x for x in items[1:])
But the slice operator creates a new list, which is not even necessary to do in many cases. Ideally, I'd like some kind of slicing function that creates generators, as opposed to new list objects. Something similar to this could be accomplished by creating a generator expression that uses a range
to return only certain portions of the list:
# Create a generator expression that returns everything except
# the first item in the list
#
iterrange = (x for x, idx in zip(items, range(0, len(items))) if idx != 0)
But this is sort of cumbersome. I'm wondering if there is a better, more elegant way to do this. So, what's the easiest way to slice a list so that a generator expression is created instead of a new list object?
A list in python can also contain lists inside it as elements. These nested lists are called sublists.
Use itertools.islice:
import itertools
l = range(20)
for i in itertools.islice(l,10,15):
print i
10
11
12
13
14
From the doc:
Make an iterator that returns selected elements from the iterable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With