Skip to content

Python Language Cheat Sheet

Python is a cross-platform computer programming language. It is an object-oriented, dynamically typed language originally designed for writing automation scripts (shell). With continuous updates and new features, it is increasingly used for independent, large-scale project development.

General

  • Python is case-sensitive
  • Python indices start from 0
  • Python uses whitespace (tabs or spaces) for indentation instead of curly braces.

Help

Help Homepage help()
Function Help help(str.replace)
Module Help help(re)

Modules (Libraries)

List module content dir(module1)
Load module import module1 *
Call function from module module1.func1()

The import statement creates a new namespace and executes all statements in the associated .py file within that namespace. If you want to load module content into the current namespace, use “from module1 import *”

Scalar Types

Check data type: type(variable)

Integers

int/long - Big integers are automatically converted to long integers

Floats

float - 64-bit, no "double" type

Booleans

bool - True or False

Strings

str - Python 2.x defaults to ASCII; Python 3 is Unicode

  • Strings can be single/double/triple quoted
  • A string is a sequence of characters and can be treated like any other sequence
  • Special characters can be escaped with \ or raw strings using r
    str1 = r'this\f?ff'
  • String formatting can be achieved in several ways
    template = '%.2f %s haha $%d'
    str1 = template % (4.88, 'hola', 2)

str(), bool(), int(), and float() are also explicit type conversion functions

Null Value

NoneType(None) - Python ’null’ value (only one instance of the None object exists)

  • None is not a reserved keyword, but the unique instance of “NoneType”
  • None is a common default value for optional function parameters:
    def func1(a, b, c = None)
  • Common usage of None:
    if variable is None :

Date and Time

datetime - Built-in Python “datetime” module provides “datetime”, “date”, “time” types.

  • “datetime” combines information stored in “date” and “time”
    Create datetime from string dt1 = datetime.strptime(‘20091031’, ‘%Y%m%d’)
    Get “date” object dt1.date()
    Get “time” object dt1.time()
    Format datetime to string dt1.strftime(’%m/%d/%Y %H:%M’)
    Modify field value dt2 = dt1.replace(minute = 0, second=30)
    Get difference diff = dt1 - dt2 # diff is a ‘datetime.timedelta’ object

Data Structures

Tuples

A tuple is a fixed-length, immutable sequence.

Create tuple tup1=4,5,6 or tup1 = (6,7,8)
Create nested tuple tup1 = (4,5,6), (7,8)
Convert sequence/iterator to tuple tuple([1, 0, 2])
Concatenate tuples tup1 + tup2
Unpack tuple a, b, c = tup1
Swap variables b, a = a, b

Lists

A list is a variable-length, mutable sequence.

Create list list1 = [1, ‘a’, 3] or list1 = list(tup1)
Concatenate lists list1 + list2 or list1.extend(list2)
Append to list list1.append(‘b’)
Insert at position list1.insert(posIdx, ‘b’)
Remove by index valueAtIdx = list1.pop(posIdx)
Remove first occurrence list1.remove(‘a’)
Check if exists 3 in list1 => True
Sort list list1.sort()
Sort with custom key list1.sort(key = len) # Sort by length

Note:

  • “Start” index is inclusive, “Stop” index is exclusive.
  • start/stop can be omitted, defaults to start/end.

Slicing

Sequence types include ‘str’, ‘array’, ’tuple’, ’list’, etc.

list1[start:stop]
list1[start:stop:step]
list1[::2]
str1[::-1]

Dictionaries (Hash)

Create dictionary dict1 ={‘key1’ :‘value1’, 2 :[3, 2]}
Construct from zip dict(zip(keyList, valueList))
Get element dict1[‘key1’]
Change/Add element dict1[‘key1’] = ’newValue’
Get with default dict1.get(‘key1’, defaultValue)
Check if key exists ‘key1’ in dict1
Delete element del dict1[‘key1’]
Get keys dict1.keys()
Get values dict1.values()
Update values dict1.update(dict2) # dict1 is merged with dict2

Sets

A set is an unordered collection of unique elements.

Create set set([3, 6, 3]) or {3, 6, 3}
Is subset set1.issubset(set2)
Is superset set1.issuperset(set2)
Equality set1 == set2
Union (or) set1
Intersection (and) set1 & set2
Difference set1 - set2
Symmetric diff (xor) set1 ^ set2

Functions

  • Basic form

    def func1(posArg1, keywordArg1 = 1, ..):
  • “Functions are objects” common usage:

    def func1(ops = [str.strip, user_define_func, ..], ..):
        for function in ops:
            value = function(value)
  • Return values

    • If no return statement, returns None.
    • Return multiple values via tuple
    return (value1, value2)
    
    value1, value2 = func1(..)
  • Anonymous Functions (Lambda)

    lambda x : x * 2
    # Equivalent to:
    # def func1(x) : return x * 2

Common Functions

  1. Enumerate: returns (index, value) tuples.

    for key, val in enumerate(collection):
  2. Sorted: returns a new sorted list from any iterable.

    sorted([2, 1, 3]) => [1, 2, 3]
  3. Zip: groups elements from iterables into tuples.

    zip(seq1, seq2) => [('seq1_1', 'seq2_1'), (..), ..]
  4. Reversed: returns a reversed iterator.

    list(reversed(range(10)))

Control Flow

  1. if/else Operators:

    Check if same object var1 is var2
    Check if different object var1 is not var2
    Check if same value var1 == var2
  2. for Loop:

    for element in iterator :
  3. pass: A null operation, used as a placeholder.

  4. Ternary Expression

    value = true-expr if condition else false-expr
  5. There is no switch/case; use if/elif/else.

Object-Oriented Programming

  1. object is the base for all Python types.

  2. Everything (numbers, strings, functions, classes, modules, etc.) is an object; every object has a ’type’. Variables are pointers to objects in memory.

  3. Basic Class Structure

    class MyObject(object):
        # 'self' is equivalent to 'this' in Java/C++
        def __init__(self, name):
            self.name = name
    
        def memberFunc1(self, arg1):
            ..
    
        @staticmethod
        def classFunc2(arg1):
            ..
    
    obj1 = MyObject('name1') 
    obj1.memberFunc1('a') 
    MyObject.classFunc2('b')
  4. Interactive Tools:

    dir(variable1) # List all available methods on the object

String Operations

Join list/tuple with a separator:

', '.join([ 'v1', 'v2', 'v3']) => 'v1, v2, v3'

Format string:

string1 = 'My name is {0} {name}'
newString1 = string1.format('Sean', name = 'Chen')

Split string:

sep = '-'
stringList1 = string1.split(sep)

Slice string:

start = 1
string1[start:8]

Zero-pad string:

month = '5'
month.zfill(2) => '05' 
month = '12'
month.zfill(2) => '12'

Exception Handling

  1. Basic Form
try:
    ..
except ValueError as e:
    print(e)
except (TypeError, AnotherError):
    ..
except:
    ..
finally:
    ..
  1. Raising Exceptions
raise AssertionError # Assertion failed
raise SystemExit # Request program exit
raise RuntimeError('Error message :..')

Comprehensions (List, Set, Dict)

Syntactic sugar for cleaner code.

  1. List Comprehension:

    Creates a new list by filtering and transforming elements.

    Form:

    [expr for val in collection if condition]

    Equivalent to:

    result = []
    for val in collection:
        if condition:
            result.append(expr)
  2. Dictionary Comprehension:

    {key-expr : value-expr for value in collection if condition}
  3. Set Comprehension: Same as list comprehension but with {}.

  4. Nested List Comprehension:

    Form:

    [expr for val in collection for innerVal in val if condition]