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 automated scripts (shell). With the continuous update of versions and the addition of new language features, it is increasingly used for the development of independent, large-scale projects.

General

  • Python is case-sensitive
  • Python indexing starts at 0
  • Python uses whitespace (tabs or spaces) to indent code instead of curly braces.

Help

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

Modules (Libraries)

List module contents 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 .py file associated with that namespace. If you want to load module content into the current namespace, use “from module1 import *”

Scalar Types

Check data type: type(variable)

Integer

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

Float

float - 64-bit, no “double” type

Boolean

bool - True or False

String

str - Python 2.x default: ASCII; Python 3: Unicode

  • Strings can be single quotes/double quotes/triple quotes
  • A string is a sequence of characters, so it can be treated like any other sequence
  • Special characters can be completed by starting with \ or r
    str1 = r'this\f?ff'
  • String formatting can be achieved in multiple ways
    template = '%.2f %s haha $%d'
    str1 = template % (4.88, 'hola', 2)

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

Null

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

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

Datetime

datetime - Built-in python “datetime” module, providing “datetime”, “date”, “time” and other 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 values 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 or 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 of elements.

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 specified position list1.insert(posIdx, ‘b’) **
Remove element by index valueAtIdx = list1.pop(posIdx)
Remove first occurrence of value list1.remove(‘a’)
Check if value exists in list 3 in list1 => True ***
Sort list list1.sort()
Sort using user-provided function list1.sort(key = len) # Sort by length

Note:

  • “Start” index is included, but “stop” index is not.
  • start/stop can be omitted, defaulting to start/end.

Slicing

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

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

Dictionaries (Hashes)

Create dictionary dict1 ={‘key1’ :‘value1’, 2 :[3, 2]}
Construct dictionary by mapping function dict(zip(keyList, valueList))
Get element dict1[‘key1’]
Change/Add element dict1[‘key1’] = ’newValue’
Get value, return default if not exists dict1.get(‘key1’, defaultValue)
Check if key exists ‘key1’ in dict1
Delete element del dict1[‘key1’]
Get Key list dict1.keys()
Get Value list dict1.values()
Update Values dict1.update(dict2) # dict1 values replaced by dict2

Sets

A set is an unordered collection of unique elements.

Create set set([3, 6, 3]) or {3, 6, 3}
Check if set1 is a subset of set2 set1.issubset(set2)
Check if set2 is a subset of set1 set1.issuperset(set2)
Check if sets are identical set1 == set2
Union (or) set1
Intersection (and) set1 & set2
Difference set1 - set2
Symmetric difference (xor) set1 ^ set2

Functions

  • Basic form

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

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

    • If there is no return statement at the end of a function, it doesn’t return any value.
    • Return multiple values via a tuple object
     return (value1, value2)
    
     value1, value2 = func1(..)
  • Anonymous functions (Lambda)

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

Commonly Used Functions

  1. Enumerate returns a sequence (key, val) tuple, where key is the index of the current item.

    for key, val in enumerate(collection):
  2. Sorted sorts all iterable objects.

    sorted([2, 1, 3]) => [1, 2, 3]
  3. Zip packs corresponding elements from objects into tuples and returns a list of these tuples.

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

    list(reversed(range(10)))

Control and Flow

  1. Operators for “if else” conditions:

    Check if two variables are the same object var1 is var2
    Check if two variables are different objects var1 is not var2
    Check if two variables have the same value var1 == var2
  2. Common usage of for operator:

    for element in iterator :
  3. ‘pass’ - Does nothing, generally used as a placeholder statement.

  4. Ternary expression

    value = true-expr if condition else false-expr
  5. No switch/case statement, use if/elif instead.

Object-Oriented

  1. ‘object’ is the base for all Python types

  2. Everything (numbers, strings, functions, classes, modules, etc.) is an object, and each object has a ’type’. Object variables are pointers to their location in memory.

  3. Basic form of an object

    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 tool:

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

String Operations

Join lists/tuples using a delimiter

', '.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)

Get substring

start = 1
string1[start:8]

Pad string with zeros

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. Manually raise exceptions
raise AssertionError # Assertion failed
raise SystemExit # Request program exit
raise RuntimeError('Error message :..')

List, Set, and Dictionary Comprehensions

Syntactic sugar to make code easier to read and write.

  1. List comprehension

    Concisely form a new list by filtering elements of a collection and transforming the elements that pass the filter in a single expression.

    Basic form

    [expr for val in collection if condition]

    Shortcut:

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

    The filter condition can be omitted, leaving only the expression.

  2. Dictionary comprehension

    {key-expr : value-expr for value in collection if condition}
  3. Set comprehension

    Basic form: Same as list comprehension, just use {} instead of []

  4. Nested list comprehension

    Basic form:

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