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

Bialecki picture Bialecki · Apr 22, 2010 · Viewed 61.6k times · Source

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?

Answer

Mike Graham picture Mike Graham · Apr 22, 2010

The normal way would be slicing:

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