Basic Python Commands

type(x) #to get the data type of a variable
len(x)  #gives the length of the list/array 
#Profile functions 
import cProfile
cProfile.run('cdfmvna(aa,rr,ss)',sort=1)

# function definition
def square(x):
    return x**2
    
#Get and set working directory
import os
os.getcwd()
os.chdir('C:\\Users\\sidharthanr\\Temp')
os.listdir('C:\\Users\\sidharthanr\\Temp') # lists all files

import sys
sys.exit("Error message")  #To stop the program execution progrmatically
sys.path.append('C:\\Temp') #after this modules in this directory can be imported
print("\n".join(sys.path)) # prints all the folders in the system path
#Get Time  for time consumed computations
import time
ts = time.time()

hrs = raw_input("Enter Name:") # to enter data from command prompt

del inpMatPD # Delete an object
__val = gc.collect() #Force garbage collection as we are deleting large objects

#Read last N lines from a file
from collections import deque
with open('data.csv', 'r') as f:
    q = deque(f, 2)  # reads last two lines

Python commands with evaluation

print(list(xrange(4))) #xrange used for iterators
print('4'.zfill(3)) #Padding Zeros in a string
print(5%2) # modulus operator 

#Multiple list counters - like a Cartesian product
print([prefix+'_'+elt for elt in ['aa','bb', 'cc'] for prefix in ('p1','p2') ])
## [0, 1, 2, 3]
## 004
## 1
## ['p1_aa', 'p2_aa', 'p1_bb', 'p2_bb', 'p1_cc', 'p2_cc']
#Equivalent of R match function (with zero indexing)
match = lambda a, b: [ b.index(x) if x in b else None for x in a ]
print(match([2,1],[1,3,1,3]))
## [None, 0]
#Subset a list using another Boolean list
from itertools import compress
list_a = [1, 2, 4, 6]
fil = [True, False, True, False]
print(list(compress(list_a, fil)))
## [1, 4]

Unpacking a list of lists

LofL = [['x01', 'x02'], ['x03', 'x04'], ['x05', 'x06']] # This is a list of list

flat_list = [item for sublist in LofL for item in sublist]
print(flat_list)
# This is equivalent to below
flat_list=[]
for sublist in LofL:
    for item in sublist:
        flat_list.append(item)
        
## ['x01', 'x02', 'x03', 'x04', 'x05', 'x06']

String Operations

s = "  \t a string example\t  "
print(s.strip()) 
print(s.rstrip()) #Whitespace on the right side:
print(s.lstrip()) #Whitespace on the left side:
print(s.strip(' \t\n\r')) #strip arbitrary characters to any of these functions like this:
str = "this is string example....wow!!! this is really string";
print(str.replace("is", "was"))
## a string example
##       a string example
## a string example   
## a string example
## thwas was string example....wow!!! thwas was really string

Time and Date

import time
from datetime import datetime
import pytz

print(datetime.fromtimestamp(1284286794)) #Convert seconds from epoch to datetime object
print(datetime.now()) # Current time
print(datetime.now(pytz.timezone('UTC')).astimezone(pytz.timezone('US/Eastern')))
## 2010-09-12 03:19:54
## 2017-08-23 22:59:22.519000
## 2017-08-24 01:59:22.519000-04:00

Itertools Pacakge

import itertools
print list(itertools.permutations([1,2,3], 2))
print list(itertools.combinations([1,2,3], 2))
## [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
## [(1, 2), (1, 3), (2, 3)]