Uncategorized

enumerate()

I was hoping to regularly update, but revisions and data collection have gotten in the way (not a bad problem to have). This is just a short shout-out to the wonderful enumerate() function in Python3.

It adds indexing to iteration. So, instead of:

mylist = [1,2,3,4,5]

target = 4
for ii in range(len(mylist)):
    if mylist[ii] == target:
        break

print('target (%d) found at %d' % (target, ii))

You can do:

mylist = [1,2,3,4,5]

target = 4
for ii, item in enumerate(mylist):
    if item == target:
        break

print('target (%d) found at %d' % (target, ii))

Granted, that's a pretty simple case, and you don't gain much. However, I've been working on rescoring/relabeling trigger codes in EEG timing files. The files are ~500 lines of text. Each event has an index, timestamp, description, type, and duration. Those five values are separated by commas, so my solution was to create a list of lists (the header lines in the timing file prevented me from simply importing it into a pandas dataFrame object, and I didn't feel like taking the time to figure out how to work around that).

In this situation, I need to be able to search for events by description and timestamp. Without enumerate, the code looks something like this:

def find_desc(event_log, desc):
    """
    Returns the index within 'event_log' of the each event
    with description equal to 'desc'
    """"

    found_indices = []
    for ii in range(len(event_log)):
        event = event_log[ii]
        if desc in event:
            found_indices.append(ii)

    return(found_indices)

However, with enumerate() - and some helpful list comprehension, this can be reduced to a single line:

def find_desc_elegant(event_log, desc):
    """
    Returns the index within 'event_log' of the each event
    with description equal to 'desc' using enumerate and list comprehension
    """"

    found_indices = [(ii, event_log.index(desc))
                     for ii, event_log in enumerate(event_log)
                     if desc in event_log]
    return(found_indices)