tags:

views:

204

answers:

4

Say I want I've got a list and I want to iterate over the first n of them. What's the most concise way to write this in Python?

+1  A: 

Python lists are O(1) random access, so just:

for i in xrange(n):
    print list[i]
Michael Mrozek
Tinkering with indices is usually something worth striving to avoid.
Mike Graham
Yeah, slicing is better; I didn't think of it
Michael Mrozek
+5  A: 

I'd probably use itertools.islice (<- follow the link for the docs), which has the benefit of working with any iterable object.

Michał Marczyk
Note that when you have a list, it's usually simpler just to use slicing (unless you have to worry about memory usage issues or something like that). If this wasn't the *first* chunk but if it was some later chunk, normal slicing can be faster as well as nicer-looking.
Mike Graham
Fair enough. Plus regular slicing is more concise, which the OP apparently cares about...
Michał Marczyk
+16  A: 

The normal way would be slicing:

for item in your_list[:n]: 
    ...
Mike Graham
+1  A: 

You can just slice the list:

>>> l = [1, 2, 3, 4, 5]
>>> n = 3
>>> l[:n]
[1, 2, 3]

and then iterate on the slice as with any iterable.

ezod
Slicing seems like the obvious, concise, clear solution.
Mike Graham