Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most Pythonic for / enumerate loop?

I have a loop condition:

for count, item in enumerate(contents):

but only want to use the first 10 elements of contents. What is the most pythonic way to do so?

Doing a:

if count == 10: break

seems somewhat un-Pythonic. Is there a better way?

like image 406
Dirk Avatar asked Jan 06 '14 14:01

Dirk


People also ask

Does enumerate increase time complexity?

@10'004: enumerate() may work with infinite generators and therefore it does not copy its input. Though it won't change the time complexity even if it did (for a finite input).

Are for loops Pythonic?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

Is enumerate or range faster?

enumerate() is faster when you want to repeatedly access the list/iterable items at their index. When you just want a list of indices, it is faster to use len() and range().

What is enumerate in for loop?

Python's enumerate() lets you write Pythonic for loops when you need a count and the value from an iterable. The big advantage of enumerate() is that it returns a tuple with the counter and value, so you don't have to increment the counter yourself.


1 Answers

Use a slice (slice notation)

for count, item in enumerate(contents[:10]):

If you are iterating over a generator, or the items in your list are large and you don't want the overhead of creating a new list (as slicing does) you can use islice from the itertools module:

for count, item in enumerate(itertools.islice(contents, 10)):

Either way, I suggest you do this in a robust manner, which means wrapping the functionality inside a function (as one is want to do with such functionality - indeed, it is the reason for the name function)

import itertools

def enum_iter_slice(collection, slice):
    return enumerate(itertools.islice(collection, slice))

Example:

>>> enum_iter_slice(xrange(100), 10)
<enumerate object at 0x00000000025595A0>
>>> list(enum_iter_slice(xrange(100), 10))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
>>> for idx, item in enum_iter_slice(xrange(100), 10):
    print idx, item

0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

If you were using enumerate and your count variable just to check the items index (so that using your method you could exit/break the loop on the 10th item.) You don't need enumerate, and just use the itertools.islice() all on its own as your function.

for item in itertools.islice(contents, 10):
like image 197
Inbar Rose Avatar answered Oct 07 '22 00:10

Inbar Rose