Python -- list comprehension with try/exception and nested conditional
Question: This code should find the mode of a list in O(n) linear time. I want to turn
this into a list comprehension because I'm teaching myself Python, and am
trying to improve my list comprehension skills.  
These were informative but don't really answer my question:

[Convert nested loops and conditions to a list
comprehension](http://stackoverflow.com/questions/19346063/convert-nested-
loops-and-conditions-to-a-list-comprehension)

[`elif` in list comprehension
conditionals](http://stackoverflow.com/questions/9987483/elif-in-list-
comprehension-conditionals)

[Nested list comprehension
equivalent](http://stackoverflow.com/questions/11598880/nested-list-
comprehension-equivalent)

The problem that I'm running into is nesting the if's and the try/except. I'm
sure this is simple question so a junior Python programmer might have the
answer quickly.

    
    
    def mode(L):
        # your code here
        d = {}; mode = 0; freq = 0
        for j in L:
            try:
                d[j] += 1
                if d[j] > freq:
                    mode = j; freq = d[j]
            except(KeyError): d[j] = 1
        return mode
    

Note that `L` parameter is a list of ints like this:

    
    
    L = [3,4,1,20,102,3,5,67,39,10,1,4,34,1,6,107,99]
    

I was thinking something like:

    
    
    [try (d[j] += 1) if d[j] > freq (mode = j; freq = d[j]) except(KeyError): d[j] = 1 for j in L]
    

But I don't have enough duct tape to fix how badly the syntax is off with that
thing.


Answer: I know you're learning comprehensions, but you can do this with a default
dictionary, or a Counter too.

    
    
    import collections
    def mode(L):
        # your code here
        d = collections.defaultdict(lambda: 1); mode = 0; freq = 0
        for j in L:
                d[j] += 1
                if d[j] > freq:
                    mode = j; freq = d[j]
        return mode
    

Better still, when you are not trying to learn comprehensions:

    
    
    import collections
    def mode(L):
        collections.Counter(L).most_common(1)[0][0]
    

