Python Cheat Sheet Just The Basics - Arianne Colton And Sean Chen Page 2

ADVERTISEMENT

o
-o
F
e
h
bject
rienteD
unctions
xception
anDlinG
p
roGramminG
Python is pass by reference, function arguments
1. Basic Form :
• Application :
are passed by reference.
1. 'object' is the root of all Python types
try:
sorted(set('abc
bcd')) => [' ',
..
• Basic Form :
2. Everything (number, string, function, class, module,
'a', 'b', 'c', 'd']
except
ValueError
as e:
etc.) is an object, each object has a 'type'. Object
# 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.
except:
other sequences to create a list of tuples :
..
Note :
sys.getrefcount(5)
=>
x
finally:
zip(seq1, seq2) =>
• Keyword arguments MUST follow positional
# clean up, e.g. close db
a
= 5,
b
=
a
..
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
• Zip can take arbitrary number of sequences.
expressions are evaluated immediately.
raise AssertionError # assertion failed
However, the number of elements it produces is
sys.getrefcount(5)
=>
x
+
2
# request program exit
raise SystemExit
determined by the 'shortest' sequence.
• Function Call Mechanism :
raise
RuntimeError('Error message :
del(a); sys.getrefcount(5) =>
x
+
1
• Application : Simultaneously iterating over multiple
..')
1. All functions are local to the module level
sequences :
scope. See 'Module' section.
4. Class Basic Form :
2. Internally, arguments are packed into a tuple
for i, (a, b) in
l
, s
D
class MyObject(object):
ist
et anD
ict
and dict, function receives a tuple 'args' and
enumerate(zip(seq1, seq2)):
# 'self' is equivalent of 'this' in Java/C++
dict 'kwargs' and internally unpack.
c
def __init__(self, name):
omprehansions
• Unzip - another way to think about this is
• Common usage of 'Functions are objects' :
self.name
=
name
converting a list of rows to a list of columns.
def
func1(ops
= [str.strip,
user_
Syntactic sugar that makes code easier to read and write
def memberFunc1(self, arg1):
define_func, ..], ..):
seq1,
seq2
= zip(*zipOutput)
..
1. List comprehensions
for
function
in ops:
value
= function(value)
@staticmethod
• Concisely form a new list by filtering the elements
4. Reversed iterates over the elements of a sequence
def classFunc2(arg1):
of a collection and transforming the elements
in reverse order.
RETURN VALUES
passing the filter in one concise expression.
..
• Basic form :
• None is returned if end of function is reached
obj1
= MyObject('name1')
*
list(reversed(range(10)))
without encountering a return statement.
obj1.memberFunc1('a')
[expr
for
val
in
collection
if condition]
MyObject.classFunc2('b')
• Multiple values return via ONE tuple object
* reversed() returns the iterator,
makes
list()
A shortcut for :
it a list.
5. Useful interactive tool :
return (value1, value2)
result = []
value1,
value2
= func1(..)
for
val
in collection:
# list all methods available on
dir(variable1)
c
F
the object
if condition:
ontrol anD
low
ANONYMOUS
(AKA LAMBDA) FUNCTIONS
result.append(expr)
• What is Anonymous function?
The filter condition can be omitted, leaving only the
1. Operators for conditions in 'if else' :
A simple function consisting of a single statement.
c
s
expression.
ommon
trinG
lambda
x
:
x
*
2
Check if two variables are
2. Dict Comprehension
var1
is
var2
operations
same object
# def func1(x) : return x * 2
• Basic form :
. . . are different object
var1
is not
var2
• Application of lambda functions : 'curring' aka
:
{key-expr
value-expr
for
value
in
Concatenate
Check if two variables have
', '.join([ 'v1', 'v2',
var1
==
var2
deriving new functions from existing ones by
List/Tuple with
collection
if condition}
same value
'v3']) =>
'v1, v2, v3'
Separator
partial argument application.
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,
{name}'
compound conditions, not &&, ||, !.
with curly braces instead of
60)
[]
Format String
newString1
= string1.
2. Common usage of 'for' operator :
format('Sean',
name
=
4. Nested list Comprehensions
USEFUL FUNCTIONS
(FOR DATA STRUCTURES)
'Chen')
Iterating over a collection (i.e. list
for
element
in
• Basic form :
1. Enumerate returns a sequence (i, value) tuples
or tuple) or an iterator
iterator :
sep = '-';
where i is the index of current item.
. . . If elements are sequences,
for a, b,
c
in
[expr
for
val
in
collection
for
stringList1
=
Split String
can be 'unpack'
iterator :
innerVal
in
val
if condition]
string1.split(sep)
for i,
value
in enumerate(collection):
3. 'pass' - no-op statement. Used in blocks where no
action is to be taken.
• Application : Create a dict mapping of value
Get Substring start = 1;
string1[start:8]
Created by Arianne Colton and Sean Chen
of a sequence (assumed to be unique) to their
4. Ternary Expression - aka less verbose 'if else'
locations in the sequence.
• Basic Form :
month
= '5';
2. Sorted returns a new sorted list from any sequence
month.zfill(2) => '05'
String Padding
Based on content from
value
=
true-expr
if
condition
with Zeros
else
false-expr
month
= '12';
'Python for Data Analysis' by Wes McKinney
sorted([2, 1, 3]) => [1, 2, 3]
month.zfill(2) => '12'
5. No switch/case statement, use if/elif instead.
Updated: May 3, 2016

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 2