How to iterate over the first n elements of a list?

PythonListSlice

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

The normal way would be slicing:

for item in your_list[:n]: 
    ...

Solution 2 - Python

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.

Solution 3 - Python

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.

Solution 4 - Python

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

for i in xrange(n):
    print list[i]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBialeckiView Question on Stackoverflow
Solution 1 - PythonMike GrahamView Answer on Stackoverflow
Solution 2 - PythonMichał MarczykView Answer on Stackoverflow
Solution 3 - PythonezodView Answer on Stackoverflow
Solution 4 - PythonMichael MrozekView Answer on Stackoverflow