78

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
  • 97,041
  • 11
  • 181
  • 245
Bialecki
  • 30,061
  • 36
  • 87
  • 109

4 Answers4

122

The normal way would be slicing:

for item in your_list[:n]: 
    ...
Mike Graham
  • 73,987
  • 14
  • 101
  • 130
  • 6
    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
41

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.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Michał Marczyk
  • 83,634
  • 13
  • 201
  • 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
13

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
  • 73,987
  • 14
  • 101
  • 130
ezod
  • 7,261
  • 2
  • 24
  • 34
2

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

for i in xrange(n):
    print list[i]
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175