Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: iterate over a sublist

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?

like image 830
Channel72 Avatar asked Jul 08 '12 13:07

Channel72


People also ask

Is Python a subList?

A list in python can also contain lists inside it as elements. These nested lists are called sublists.


1 Answers

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

like image 133
Sebastian Hoffmann Avatar answered Nov 15 '22 20:11

Sebastian Hoffmann