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?
views:
204answers:
4
+1
A:
Python lists are O(1) random access, so just:
for i in xrange(n):
print list[i]
Michael Mrozek
2010-04-22 03:40:49
Tinkering with indices is usually something worth striving to avoid.
Mike Graham
2010-04-22 03:52:16
Yeah, slicing is better; I didn't think of it
Michael Mrozek
2010-04-22 04:10:42
+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
2010-04-22 03:41:03
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
2010-04-22 03:51:02
Fair enough. Plus regular slicing is more concise, which the OP apparently cares about...
Michał Marczyk
2010-04-22 04:13:01
+16
A:
The normal way would be slicing:
for item in your_list[:n]:
...
Mike Graham
2010-04-22 03:45:51
+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
2010-04-22 03:46:06