0% found this document useful (0 votes)
14 views

python_cheet_sheet

Cheat sheet for python programming language

Uploaded by

Aman Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

python_cheet_sheet

Cheat sheet for python programming language

Uploaded by

Aman Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Datas tructures

Python Cheat Sheet Create Tuple tup1 = 4, 5, 6 or


tup1 = (6,7,8)

Note :
• 'start' index is included, but 'stop' index is NOT.
Create Nested Tuple tup1 = (4,5,6), (7,8)
• start/stop can be omitted in which they default to
Convert Sequence or the start/end.
Iterator to Tuple tuple([1, 0, 2])
Concatenate Tuples tup1 + tup2
Unpack Tuple a, b, c = tup1 § Application of 'step' :
Application of Tuple Take every other element list1[::2]

General scalar t ypes Swap variables b, a = a, b


Reverse a string str1[::-1]

LIST DICT (HASH MAP)


• Python is case sensitive
* str(), bool(), int() and float() are also explicit type One dimensional, variable length, mutable (i.e.
• Python index starts from 0 cast functions. contents can be modified) sequence of Python objects Create Dict dict1 ={'key1' :'value1',2
• Python uses whitespace (tabs or spaces) to indent of ANY type. :[3, 2]}
5. NoneType(None) - Python 'null' value (ONLY Create Dict from
code instead of using braces. Sequence
dict(zip(keyList,
one instance of None object exists) Create List list1 = [1, 'a', 3] or valueList))
HELP • None is not a reserved keyword but rather a
list1 = list(tup1) Get/Set/Insert Element dict1['key1']*
Concatenate Lists* list1 + list2 or dict1['key1'] = 'newValue'
unique instance of 'NoneType' list1.extend(list2) Get with Default Value dict1.get('key1',
Help Home Page help() • None is common default value for optional Append to End of List list1.append('b') defaultValue) **
Function Help help(str.replace) function arguments : Insert to Specific list1.insert(posIdx, Check if Key Exists 'key1' in dict1
Position 'b') ** Delete Element del dict1['key1']
Module Help help(re)
Inverse of Insert Get Key List
def func1(a, b, c = None) valueAtIdx = list1. dict1.keys() ***
MODULE (AKA LIBRARY) Remove First Value
pop(posIdx) Get Value List
dict1.values() ***
• Common usage of None :
Python module is simply a '.py' file from List list1.remove('a') Update Values dict1.update(dict2)
if variable is None : Check Membership 3 in list1 => True *** # dict1 values are replaced by dict2
List Module Contents dir(module1) Sort List list1.sort()
Load Module import module1 * 6. datetime - built-in python 'datetime' module Sort with User- * 'KeyError' exception if the key does not exist.
provides 'datetime', 'date', 'time' types. list1.sort(key = len)
Call Function from Module Supplied Function # sort by length
module1.func1()
• 'datetime' combines information stored in 'date' ** 'get()' by default (aka no 'defaultValue') will
and 'time' return 'None' if the key does not exist.
* import statement creates a new namespace and Create datetime * List concatenation using '+' is expensive since
executes all the statements in the associated .py from String a new list must be created and objects copied *** Returns the lists of keys and values in the same
file within that namespace. If you want to load the dt1 = datetime. order. However, the order is not any particular
module's content into current namespace, use 'from Get 'date' object strptime('20091031', over. Thus, extend() is preferable.
module1 import * ' '%Y%m%d') order, aka it is most likely not sorted.
Get 'time' object ** Insert is computationally expensive compared
Format datetime
dt1.date()
with append. Valid dict key types
to String dt1.time() • Keys have to be immutable like scalar types (int,
*** Checking that a list contains a value is lot slower
float, string) or tuples (all the objects in the tuple
scalar t ypes Change Field
Value
dt1.strftime('%m/%d/%Y
%H:%M')
than dicts and sets as Python makes a linear
scan where others (based on hash tables) in
need to be immutable too)
constant time. • The technical term here is 'hashability',
Get Difference dt2=dt1.replace(minute =
Check data type : type(variable) 0, second=30)
check whether an object is hashable with the
hash('this is string'), hash([1, 2])
SIX COMMONLY USED DATA TYPES
diff = dt1 - dt2 Built-in 'bisect module ‡
# diff is a 'datetime.timedelta' object - this would fail.
• Implements binary search and insertion into a
1. int/long* - Large int automatically converts to long Note : Most objects in Python are mutable except
sorted list SET
2. float* - 64 bits, there is no 'double' type for 'strings' and 'tuples' • 'bisect.bisect' finds the location, where 'bisect.
insort' actually inserts into that location. • A set is an unordered collection of UNIQUE
3. bool* - True or False elements.
4. str* - ASCII valued in Python 2.x and Unicode in Python 3 ‡ WARNING : bisect module functions do not • You can think of them like dicts but keys only.
• String can be in single/double/triple quotes Datas tructures check whether the list is sorted, doing so would
be computationally expensive. Thus, using them Create Set set([3,6,3]) or
{3, 6,3}
• String is a sequence of characters, thus can be in an unsorted list will succeed without error but
treated like other sequences Test Subset set1.issubset ( set2)
• Note : All non-Get function call i.e. list1.sort() may lead to incorrect results. Test Superset
Special character can be done via \ or preface set1.issuperset ( set2)
examples below are in-place (without creating a new SLICING FOR SEQUENCE TYPES† Test sets have same
with r object) operations unless noted otherwise. content set1 == set2

str1 = r'this\f?ff'
† Sequence types include 'str', 'array', 'tuple', 'list', etc. • Set operations :
• String formatting can be done in a number of ways
TUPLE Union(aka 'or') set1 | set2
template = '%.2f %s haha $%d'; One dimensional, fixed-length, immutable sequence Notation list1[start:stop] Intersection (aka 'and') set1 & set2
str1 = template % (4.88, 'hola', 2) of Python objects of ANY type. list1[start:stop:step] Difference set1 - set2
(If step is used) § Symmetric Difference (aka 'xor') set1 ^ set2
Functions o bject -orienteD exception
hanDlinG
Python is pass by reference , function arguments • Application :
proGramminG 1. Basic Form :
are passed by reference. 1. 'object' is the root of all Python types try:
sorted(set('abc bcd')) => [' ',
• Basic Form : 'a', 'b', 'c', 'd'] 2. Everything (number, string, function, class, module, ..
etc.) is an object, each object has a 'type'. Object except ValueError as e:
# returns sorted unique characters print e
def func1(posArg1, keywordArg1 = variable is a pointer to its location in memory. except (TypeError, AnotherError):
1, ..): 3. Zip pairs up elements of a number of lists, tuples or 3. All objects are reference-counted. ..
other sequences to create a list of tuples : except:..
Note : sys.getrefcount(5) => x ..
• Keyword arguments MUST follow positional zip(seq1, seq2) => finally:
a = 5, b = a # clean up, e.g. close db
arguments. [('seq1_1', 'seq2_1'), (..), ..]
# This creates a 'reference' to the object on the 2. Raise Exception Manually
• Python by default is NOT "lazy evaluation", right side of =, thus both a and b point to 5
expressions are evaluated immediately. • Zip can take arbitrary number of sequences.
However, the number of elements it produces is raise AssertionError # assertion failed
sys.getrefcount(5) => x + 2 # request program exit
• Function Call Mechanism : determined by the 'shortest' sequence. raise SystemExit
raise RuntimeError('Error message :
• Application : Simultaneously iterating over multiple del(a); sys.getrefcount(5) => x + 1
1. All functions are local to the module level ..')
scope. See 'Module' section. sequences : 4. Class Basic Form :
2. Internally, arguments are packed into a tuple
l ist , s et anD Dict
for i, (a, b) in class MyObject(object):
and dict, function receives a tuple 'args' and
dict 'kwargs' and internally unpack. enumerate(zip(seq1, seq2)): # 'self' is equivalent of 'this' in Java/C++

• Common usage of 'Functions are objects' : • Unzip - another way to think about this is
converting a list of rows to a list of columns.
def __init__(self, name):
self.name = name
c omprehansions
def func1(ops = [str.strip, user_ def memberFunc1(self, arg1): Syntactic sugar that makes code easier to read and write
define_func, ..], ..):
for function in ops:
seq1, seq2 = zip(*zipOutput) .. 1. List comprehensions
value = function(value)
4. Reversed iterates over the elements of a sequence
@staticmethod • Concisely form a new list by filtering the elements
of a collection and transforming the elements
RETURN VALUES
def classFunc2(arg1):
in reverse order. passing the filter in one concise expression.
..
• None is returned if end of function is reached list(reversed(range(10))) * obj1 = MyObject('name1') • Basic form :
without encountering a return statement. obj1.memberFunc1('a') [expr for val in collection if condition]
• Multiple values return via ONE tuple object * reversed() returns the iterator, list() makes MyObject.classFunc2('b')
it a list. A shortcut for :
5. Useful interactive tool :
return (value1, value2) result = []
value1, value2 = func1(..)
dir(variable1) # list all methods available on for val in collection:
ANONYMOUS (AKA LAMBDA) FUNCTIONS control anD
Flow the object if condition:
result.append(expr)
• What is Anonymous function?
A simple function consisting of a single statement. 1. Operators for conditions in 'if else' : The filter condition can be omitted, leaving only the

lambda x : x * 2 Check if two variables are


s trinG
common expression.
2. Dict Comprehension
# def func1(x) : return x * 2
same object var1 is var2 operations • Basic form :
. . . are different object var1 is not var2
• Application of lambda functions : 'curring' aka Concatenate
{key-expr : value-expr for value in
Check if two variables have
deriving new functions from existing ones by same value
var1 == var2 List/Tuple with ', '.join([ 'v1', 'v2', collection if condition}
partial argument application. Separator 'v3']) => 'v1, v2, v3'
3. Set Comprehension
WARNING : Use 'and', 'or', 'not' operators for string1 = 'My name is {0} • Basic form : same as List Comprehension except
ma60 = lambda x : pd.rolling_mean(x,
60) compound conditions, not &&, ||, !. {name}' with curly braces instead of []
Format String
USEFUL FUNCTIONS (FOR DATA STRUCTURES) 2. Common usage of 'for' operator : newString1 = string1. 4. Nested list Comprehensions
format('Sean', name =
Iterating over a collection (i.e. list for element in 'Chen') • Basic form :
1. Enumerate returns a sequence (i, value) tuples or tuple) or an iterator iterator :
where i is the index of current item. . . . If elements are sequences, for a, b, c in Split String
sep = '-';
[expr for val in collection for
can be 'unpack' iterator : stringList1 = innerVal in val if condition]
for i, value in enumerate(collection): 3. 'pass' - no-op statement. Used in blocks where no string1.split(sep)
• Application : Create a dict mapping of value action is to be taken.
Get Substring start = 1; string1[start:8]
of a sequence (assumed to be unique) to their 4. Ternary Expression - aka less verbose 'if else'
locations in the sequence.

Data Science
• Basic Form : month = '5';
2. Sorted returns a new sorted list from any sequence String Padding month.zfill(2) => '05'
value = true-expr if condition
else false-expr with Zeros month = '12';
sorted([2, 1, 3]) => [1, 2, 3] month.zfill(2) => '12'
5. No switch/case statement, use if/elif instead.

You might also like