72

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

Rich Scriven
  • 93,629
  • 10
  • 165
  • 233
Bialecki
  • 28,323
  • 35
  • 84
  • 105

4 Answers4

113

The normal way would be slicing:

for item in your_list[:n]: 
    ...
Mike Graham
  • 69,495
  • 14
  • 96
  • 129
  • 3
    Note that this creates a copy of the first `n` elements of the list, which may be slow and memory intensive for large lists. `itertools.islice` is far more efficient (and also works with any iterable). – BallpointBen Apr 17 '18 at 22:10
36

I'd probably use itertools.islice (<- follow the link for the docs), which has the benefits of:

  • working with any iterable object
  • not copying the list

Usage:

import itertools

n = 2
mylist = [1, 2, 3, 4]
for item in itertools.islice(mylist, n):
    print(item)

outputs:

1
2

One downside is that if you wanted a non-zero start, it has to iterate up to that point one by one: https://stackoverflow.com/a/5131550/895245

Tested in Python 3.8.6.

Michał Marczyk
  • 82,286
  • 11
  • 198
  • 212
  • 2
    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 Apr 22 '10 at 03:51
  • Fair enough. Plus regular slicing is more concise, which the OP apparently cares about... – Michał Marczyk Apr 22 '10 at 04:13
11

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.

Mike Graham
  • 69,495
  • 14
  • 96
  • 129
ezod
  • 7,013
  • 2
  • 23
  • 32
2

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

for i in xrange(n):
    print list[i]
Michael Mrozek
  • 161,243
  • 28
  • 165
  • 171