Having trouble with pythonic style and list comprehension
Question: I spent yesterday writing a small script in Python, which is not my primary
language, and it left me with some questions on how to do things in proper
'pythonic' style. The task is fairly simple, I have two arrays `fieldnames`
and `values`. Imagine their contents are

    
    
    fieldnames = ['apples','oranges','pears','bananas']
    values = [None,2,None,5]
    

I need to create an array of fieldnames that only consists of indices that
correspond with values that are not None. Currently I am doing it like this:

    
    
    #print fieldnames
    usedFieldnames = []
    
    for idx,val in enumerate(values):
        if val is not None:
            usedFieldnames.append(fieldnames[idx])
    

I could be wrong, but this seems very non-pythonic to me, and I was wondering
if there was a more python-appropriate way to do this with a list
comprehension. Any help would be appreciated.


Answer: You can use [`zip()`](https://docs.python.org/2/library/functions.html#zip):

    
    
    >>> fieldnames = ['apples','oranges','pears','bananas']
    >>> values = [None,2,None,5]
    >>> [field for field, value in zip(fieldnames, values) if value is not None]
    ['oranges', 'bananas']
    

If you are using python2.x, instead of `zip()`, which creates a new list with
zipped lists, you can take an "iterative" approach and use
[`itertools.izip()`](https://docs.python.org/2/library/itertools.html#itertools.izip):

    
    
    >>> from itertools import izip
    >>> [field for field, value in izip(fieldnames, values) if value is not None]
    ['oranges', 'bananas']
    

In case of python3.x, `zip()` returns an iterator, not a list.

