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

ADVERTISEMENT

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

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 2