Python Patterns

I have now been working with Python for more than a month, here are some of the interesting patterns that I found in the language. Its a nice, clean and easy language, in particular I really enjoy the list comprehensions.


Loop over a list

    for item in items:
        print item

Loop over a dictionary

    for key, value in dictionaryname.items()

Map with list comprehensions

    [func(item) for item in items]

Map over list of lists

    [func(item) for list in lists for item in items]

Filter list

    [item for item in items if wanted(item)]

Conditions in list comprehensions

    #increase magnitude
    [item -1 if item < 0 else item + 1 for item in items]


Create a module

Create a folder with a blank file named

Import classes from modules

    from modulename import ClassName

Relative import or modules

    from ..packagename import modulename


Escape in to interpreter

    import code


Simple Benchmark

    from time import time
    t1 = time.time()
    t2 = time.time()
    print t2-t1


Raise an exception

    raise Exception("message")

Useful built-in types: ValueError, TypeError, ArithmeticError. Complete List

© 2017. All rights reserved.