Python Tutorial

Friday, December 20, 2013

python dictionary comprehensions

Python dictionary comprehensions is similar to list comprehension. Lets have some example
import os

# from a directory get each file name as key and file size as value
print {filename: os.path.getsize(filename) for filename in os.listdir(os.getcwd()) }

# initialize from 0-9 key as true
print {n: True for n in range(10)}

Python list comprehensions

Python list comprehensions provide many way to create list.
The comrehensions format is [*transform* *iteration* *filter* ].
Let's have some example.

# read a file line by line check whether or not "word" contains in each line (ignore case)
print [ line.strip("\n").lower() for line in open("a.in") if "word" in line]

# initialize array by square number
print [i**2 for i in range(10)]
# initialize array with tuples 
print [(i,i**2) for i in range(10)]

# initialize array by odd number
print [i for i in range(10) if i%2]

words = ["Life", "is", "very", "easy", "Python"]
# print first character of each word
print [word[0] for word in words]

# make all words to upper case
print [word.upper() for word in words]

# Sum each element of two array
a = [1, 2, 3]
b = [4, 5, 6]
print [a[i]+b[i] for i in range(len(a))]

Thursday, December 12, 2013

Context manager API

A context manager is enabled by the with statement, and the API involves two methods. The __enter__() method is run when execution flow enters the code block inside the with. It returns an object to be used within the context. When execution flow leaves the with block, the __exit__() method of the context manager is called to clean up any resources being used.

class Context(object):

    def __init__(self):
        print "Initialize"

    def __enter__(self):
        print "Enter"

    def __exit__(self, exc_type, exc_val, exc_tb):
        print "Exit"


with Context():
    print "Doing something"


Output:
Initialize
Enter
Doing something
Exit

Context manager API

Python file object support the context manager API to make it easy to ensure they are closed after all reading or writing is done

with open('z.txt', 'r') as f:
    data = f.read()
    print data

Output:
File content

Python enumerate

enumerate returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence.
a = ["Python","easy"]

for i, n in enumerate(a):
    print i, n


Output:
0 Python
1 easy

Python case insensitive dictionary

class CaseInsensitiveDict(dict):
    def __setitem__(self, key, value):
        key = key.lower()
        dict.__setitem__(self, key, value)

    def __getitem__(self, key):
        key = key.lower()
        return dict.__getitem__(self, key)

d = CaseInsensitiveDict()
d["Python"] = "Easy"
print d["PYTHON"]
print d["python"]

Output:
Easy
Easy

Monday, December 9, 2013

Python for loop with else clauses


Python for loop with else condition is very interesting feature. This types of feature makes code more readable and pythonic. Lets see an example.

a = [1, 3, 51, 7, 8]
print a
k = 5
for n in a:
    if n%k==0:
        print "Divisible by",k,"found"
        break
else:
    # This line will working if for loop terminate normally
    print "Divisible by",k,"not found"

print
a = [1, 3, 5, 7, 8]
print a
k = 5
for n in a:
    if n%k==0:
        print "Divisible by",k,"found"
        break
else:
    # This line will working if for loop terminate normally
    print "Divisible by",k,"not found"


Output:
[1, 3, 51, 7, 8]
Divisible by 5 not found

[1, 3, 5, 7, 8]
Divisible by 5 found