How can I limit iterations of a loop in Python?

Viewed 105667

Say I have a list of items, and I want to iterate over the first few of it:

items = list(range(10)) # I mean this to represent any kind of iterable.
limit = 5

Naive implementation

The Python naïf coming from other languages would probably write this perfectly serviceable and performant (if unidiomatic) code:

index = 0
for item in items: # Python's `for` loop is a for-each.
    print(item)    # or whatever function of that item.
    index += 1
    if index == limit:
        break

More idiomatic implementation

But Python has enumerate, which subsumes about half of that code nicely:

for index, item in enumerate(items):
    print(item)
    if index == limit: # There's gotta be a better way.
        break

So we've about cut the extra code in half. But there's gotta be a better way.

Can we approximate the below pseudocode behavior?

If enumerate took another optional stop argument (for example, it takes a start argument like this: enumerate(items, start=1)) that would, I think, be ideal, but the below doesn't exist (see the documentation on enumerate here):

# hypothetical code, not implemented:
for _, item in enumerate(items, start=0, stop=limit): # `stop` not implemented
    print(item)

Note that there would be no need to name the index because there is no need to reference it.

Is there an idiomatic way to write the above? How?

A secondary question: why isn't this built into enumerate?

6 Answers

Pass islice with the limit inside enumerate

a = [2,3,4,2,1,4]

for a, v in enumerate(islice(a, 3)): 
   print(a, v)

Output:

0 2
1 3
2 4

Why not loop until the limit or the end of list, whichever occurs earlier, like this:

items = range(10)
limit = 5
for i in range(min(limit, len(items))):
  print items[i]

Output:

0
1
2
3
4

short solution

items = range(10)
limit = 5

for i in items[:limit]: print(i)
Related