DOKK Library

Python 3 Cheat Sheet

Authors Laurent Pointal

License CC-BY-4.0

©2012-2015 - Laurent Pointal Mémento v2.0.6
License Creative Commons Attribution 4                                             Python 3 Cheat Sheet                                         Latest version on :
 integer, float, boolean, string, bytes Base Types                                   ◾ ordered sequences, fast index access, repeatable values                       Container Types
     int 783 0 -192 0b010 0o642 0xF3                                                            list [1,5,9]            ["x",11,8.9]                             ["mot"]         []
                        zero              binary    octal                   hexa              tuple (1,5,9)               11,"y",7.4                             ("mot",)        ()
 float 9.23 0.0 -1.7e-6
                        -6                                                            Non modifiable values (immutables) ☝ expression with only comas →tuple
  bool True False   ×10
                                                                                               str bytes (ordered sequences of chars / bytes)
   str "One\nTwo"   Multiline string:                                                                                                                                                          b""
            escaped new line                   """X\tY\tZ                             ◾ key containers, no a priori order, fast key access, each key is unique
                'I\'m'                         1\t2\t3"""                            dictionary   dict {"key":"value"}                        dict(a=3,b=4,k="v")                               {}
                escaped '                          escaped tab                       (key/value associations) {1:"one",3:"three",2:"two",3.14:"π"}
 bytes b"toto\xfe\775"                                                               collection     set {"key1","key2"}                       {1,9,3,0}                                  set()
                   hexadecimal octal                    ☝ immutables                 ☝ keys=hashable values (base types, immutables…)          frozenset immutable set                         empty

 for variables, functions,                    Identifiers                                                                type(expression)              Conversions
 modules, classes… names
                                                                            int("15") → 15
                                                                            int("3f",16) → 63                                                    nd
                                                                                                             can specify integer number base in 2 parameter
 a…zA…Z_ followed by a…zA…Z_0…9
 ◽ diacritics allowed but should be avoided                                 int(15.56) → 15                  truncate decimal part
 ◽ language keywords forbidden                                              float("-11.24e8") → -1124000000.0
 ◽ lower/UPPER case discrimination                                          round(15.56,1)→ 15.6             rounding to 1 decimal (0 decimal → integer number)
        ☺    a toto x7 y_max BigOne                                         bool(x) False for null x, empty container x , None or False x ; True for other x
        ☹    8y and for                                                     str(x)→ "…" representation string of x for display (cf. formatting on the back)
                                                                            chr(64)→'@' ord('@')→64                     code ↔ char
            =             Variables assignment
                                                                            repr(x)→ "…" literal representation string of x
  ☝ assignment ⇔ binding of a name with a value
  1) evaluation of right side expression value                              bytes([72,9,64]) → b'H\t@'
  2) assignment in order with left side names                               list("abc") → ['a','b','c']
x=1.2+8+sin(y)                                                              dict([(3,"three"),(1,"one")]) → {1:'one',3:'three'}
a=b=c=0 assignment to same value                                            set(["one","two"]) → {'one','two'}
y,z,r=9.2,-7.6,0 multiple assignments                                       separator str and sequence of str → assembled str
a,b=b,a values swap                                                            ':'.join(['toto','12','pswd']) → 'toto:12:pswd'
a,*b=seq unpacking of sequence in                                           str splitted on whitespaces → list of str
*a,b=seq item and list                                                         "words with spaces".split() → ['words','with','spaces']
                                    and                                     str splitted on separator str → list of str
x+=3   increment ⇔ x=x+3            *=
x-=2   decrement ⇔ x=x-2            /=                                         "1,4,8,2".split(",") → ['1','4','8','2']
x=None « undefined » constant value %=                                      sequence of one type → list of another type (via list comprehension)
 del x          remove name x                           …                      [int(x) for x in ('1','29','-3')] → [1,29,-3]
                                                      for lists, tuples, strings, bytes…                                                     Sequence Containers Indexing
     negative index            -5        -4        -3    -2         -1              Items count                        Individual access to items via lst[index]
      positive index           0          1         2      3        4           len(lst)→5                             lst[0]→10                ⇒ first one                lst[1]→20
                lst=[10, 20, 30, 40, 50]                                                                               lst[-1]→50               ⇒ last one                 lst[-2]→40
       positive slice     0          1        2        3                    4        5        ☝ index from 0
                                                                                                                        On mutable sequences (list), remove with
      negative slice      -5        -4        -3      -2                    -1               (here from 0 to 4)
                                                                                                                        del lst[3] and modify with assignment
  Access to sub-sequences via lst[start slice:end slice:step]
  lst[:-1]→[10,20,30,40] lst[::-1]→[50,40,30,20,10] lst[1:3]→[20,30]       lst[:3]→[10,20,30]
  lst[1:-1]→[20,30,40]   lst[::-2]→[50,30,10]           lst[-3:-1]→[30,40] lst[3:]→[40,50]
  lst[::2]→[10,30,50]    lst[:]→[10,20,30,40,50] shallow copy of sequence
  Missing slice indication → from start / up to end.
  On mutable sequences (list), remove with del lst[3:5] and modify with assignment lst[1:4]=[15,25]

                          Boolean Logic                                              Statements Blocks                                  Modules/Names Imports
                                                                                                                  module truc⇔file
  Comparisons : < > <= >= == !=                                                                                   from monmod import nom1,nom2 as fct
  (boolean results)       ≤ ≥ = ≠                        parent statement:                                                                →direct access to names, renaming with as
 a and b          logical and both simulta-                 statement block 1…                                    import monmod →access via monmod.nom1 …
                                                            indentation !

                                    -neously                        ⁝                                              ☝ modules and packages searched in python path (cf sys.path)
 a or b             logical or one or other                 parent statement:                                     statement block executed only
                                or both                                                                                                                        Conditional Statement
                                                                statement block2…                                 if a condition is true
 ☝ pitfall : and and or return value of a or                           ⁝                                                                                           yes         no        yes
 of b (under shortcut evaluation).                                                                                  if logical condition:                                  ?                    ?
 ⇒ ensure that a and b are booleans.                                                                                                                                                             no
 not a              logical not
                                                         next statement after block 1                                    statements block
 True                                                                                                             Can go with several elif, elif... and only one
                    True and False constants                     ☝ configure editor to insert 4 spaces in                                        if age<=18:
 False                                                                                                            final else. Only the block of first true
                                                                 place of an indentation tab.                                                      state="Kid"
                                                                                                                  condition is executed.         elif age>65:
 ☝ floating numbers… approximated values                                     Maths
                                                                   angles in radians                              ☝ with a var x:                  state="Retired"
                                                                                                                  if bool(x)==True: ⇔ if x:      else:
 Operators: + - * / // % **                              from math import sin,pi…                                                                  state="Active"
                                                                                                                  if bool(x)==False: ⇔ if not x:
 Priority (…) × ÷        ab                              sin(pi/4)→0.707…
                        integer ÷ ÷ remainder            cos(2*pi/3)→-0.4999…                                                                                    Exceptions on Errors
                                                                                                                  Signaling an error:
 @ → matrix × python3.5+numpy                            sqrt(81)→9.0     √                                             raise ExcClass(…)                                               error
 (1+5.3)*2→12.6                                          log(e**2)→2.0                                            Errors processing:                          normal                    processing
 abs(-3.2)→3.2                                           ceil(12.5)→13                                             try:                                        raise X()            errorraise
                                                                                                                                                              processing            processing
 round(3.57,1)→3.6                                       floor(12.5)→12                                                  normal procesising block
 pow(4,3)→64.0                                         modules math, statistics, random,                           except Exception as e:                 ☝ finally block for final processing
     ☝ usual order of operations                   decimal, fractions, numpy, etc. (cf. doc)                             error processing block           in all cases.
                              statements block executed as long as            Conditional Loop Statement                    statements block executed for each            Iterative Loop Statement
                              condition is true                                                                             item of a container or iterator
☝ beware of infinite loops!

                                                                                 yes                                                                                                            next
                                 while logical condition:                              ?                    Loop Control                    for var in sequence:                                       …
                                                                                           no                                                                                                           finish
                                     statements block                                              break     immediate exit                     statements block
                                                                                                   continue next iteration
                              s = 0 initializations before the loop                                    ☝ else block for normal          Go over sequence's values
                              i = 1 condition with a least one variable value (here i)                 loop exit.                      s = "Some text" initializations before the loop
                                                                                                        Algo:                          cnt = 0

                                                                                                                                                                                                            ☝ good habit : don't modify loop variable
                              while i <= 100:                                                                   i=100                     loop variable, assignment managed by for statement
                                  s = s + i**2
                                  i = i + 1                ☝ make condition variable change !            s= ∑ i 2                      for c in s:
                                                                                                                                             if c == "e":                        Algo: count
                              print("sum:",s)                                                                    i=1                                cnt = cnt + 1                number of e
                                                                                                                                       print("found",cnt,"'e'")                  in the string.
               print("v=",3,"cm :",x,",",y+4)                                                                   Display     loop on dict/set ⇔ loop on keys sequences
                                                                                                                            use slices to loop on a subset of a sequence

                     items to display : literal values, variables, expressions                                              Go over sequence's index
                 print options:                                                                                             ◽ modify item at index
                 ◽ sep=" "                   items separator, default space                                                 ◽ access items around index (before / after)
                                                                                                                            lst = [11,18,9,12,23,4,17]
                 ◽ end="\n"                  end of print, default new line                                                 lost = []
                 ◽ file=sys.stdout print to file, default standard output                                                   for idx in range(len(lst)):     Algo: limit values greater
                                                                                                                                val = lst[idx]              than 15, memorizing
                  s = input("Instructions:")                                                                      Input
                                                                                                                                if val > 15:                of lost values.
                               ☝ input always returns a string, convert it to required type                                         lost.append(val)
                                  (cf. boxed Conversions on the other side).                                                        lst[idx] = 15
         len(c)→ items count               Generic Operations on Containers                                                 Go simultaneously over sequence's index and values:
         min(c) max(c) sum(c)                        Note: For dictionaries and sets, these                                 for idx,val in enumerate(lst):
         sorted(c)→ list sorted copy                 operations use keys.
         val in c → boolean, membership operator in (absence not in)                                                             range([start,] end [,step])                      Integer Sequences
         enumerate(c)→ iterator on (index, value)                                                                           ☝ start default 0, end not included in sequence, step signed, default 1
         zip(c1,c2…)→ iterator on tuples containing ci items at same index
                                                                                                                            range(5)→ 0 1 2 3 4                range(2,12,3)→ 2 5 8 11
         all(c)→ True if all c items evaluated to true, else False                                                          range(3,8)→ 3 4 5 6 7              range(20,5,-5)→ 20 15 10
         any(c)→ True if at least one item of c evaluated true, else False                                                  range(len(seq))→ sequence of index of values in seq
          Specific to ordered sequences containers (lists, tuples, strings, bytes…)                                         ☝ range provides an immutable sequence of int constructed as needed
          reversed(c)→ inversed iterator c*5→ duplicate                         c+c2→ concatenate
          c.index(val)→ position                    c.count(val)→ events count                                               function name (identifier)                           Function Definition
          import copy                                                                                                                    named parameters
          copy.copy(c)→ shallow copy of container                                                                            def fct(x,y,z):
          copy.deepcopy(c)→ deep copy of container                                                                                                                                      fct
          ☝ modify original list                        Operations on Lists                                                      # statements block, res computation, etc.
          lst.append(val)      add item at end                                                                                   return res          result value of the call, if no computed
                                                                                                                                                               result to return: return None
          lst.extend(seq)      add sequence of items at end                                                                  ☝ parameters and all
          lst.insert(idx,val)  insert item at index                                                                          variables of this block exist only in the block and during the function
          lst.remove(val)      remove first item with value val                                                              call (think of a “black box”)
          lst.pop([idx])→value remove & return item at index idx (default last)                                              Advanced: def fct(x,y,z,*args,a=3,b=5,**kwargs):
          lst.sort() lst.reverse() sort / reverse liste in place                                                               *args variable positional arguments (→tuple), default values,
                                                                                                                               **kwargs variable named arguments (→dict)
            Operations on Dictionaries                                                          Operations on Sets
        d[key]=value         d.clear()                                     Operators:                                            r = fct(3,i+2,2*i)                                      Function Call
                                                                            | → union (vertical bar char)                        storage/use of          one argument per
        d[key]→ value        del d[key]                                     & → intersection                                     returned value          parameter
        d.update(d2) update/add                                             - ^ → difference/symmetric diff.                ☝ this is the use of function                           fct()             fct
                          associations                                                                                                                              Advanced:
        d.keys()                                                            < <= > >= → inclusion relations                 name with parentheses                   *sequence
        d.values() →iterable views on                                      Operators also exist as methods.                 which does the call                     **dict
        d.items() keys/values/associations
        d.pop(key[,default])→ value                                        s.update(s2) s.copy()
                                                                           s.add(key) s.remove(key)                         s.startswith(prefix[,start[,end]])         Operations on Strings
        d.popitem()→ (key,value)
        d.get(key[,default])→ value                                        s.discard(key) s.clear()                         s.endswith(suffix[,start[,end]]) s.strip([chars])
        d.setdefault(key[,default])→value                                  s.pop()                                          s.count(sub[,start[,end]]) s.partition(sep)→ (before,sep,after)
                                                                                                                            s.index(sub[,start[,end]]) s.find(sub[,start[,end]])
               storing data on disk, and reading it back                                                          Files…() tests on chars categories (ex. s.isalpha())
                                 f = open("file.txt","w",encoding="utf8")                                                   s.upper()      s.lower()           s.title()     s.swapcase()
                                                                                                                            s.casefold()        s.capitalize() [width,fill])
        file variable                       name of file
                                             opening mode                                           encoding of             s.ljust([width,fill]) s.rjust([width,fill]) s.zfill([width])
        for operations                       ◽ 'r' read
                                            on disk                                                 chars for text          s.encode(encoding)        s.split([sep]) s.join(seq)
                                             ◽ 'w' write
                                            (+path…)                                                files:
                                             ◽ 'a' append                                           utf8 ascii                    formating directives                values to format       Formatting
         cf. modules os, os.path and pathlib ◽ …'+' 'x' 'b' 't'                                     latin1 …
                                                                                                                             "modele{} {} {}".format(x,y,r)                                 str
             writing                                             ☝ read empty string if end of file              reading     "{selection:formatting!conversion}"
               f.write("coucou")                       [n])                     → next chars
               f.writelines(list of lines)           if n not specified, read up to end !                                    ◽ Selection :                 "{:+2.3f}".format(45.72793)
                                               f.readlines([n]) → list of next lines                                             2                         →'+45.728'

                                               f.readline()                 → next line                                          nom                       "{1:>10s}".format(8,"toto")
                    ☝ text mode t by default (read/write str), possible binary                                                   0.nom                     →'           toto'
                                                                                                                                 4[key]                    "{x!r}".format(x="I'm")
                    mode b (read/write bytes). Convert from/to required type !                                                   0[2]
         f.close()              ☝ dont forget to close the file after use !                                                                                →'"I\'m"'
                                                                                                                             ◽ Formatting :
         f.flush()       write cache               f.truncate([size]) resize                                                 fill char alignment sign mini width.precision~maxwidth type
         reading/writing progress sequentially in the file, modifiable with:
                                                                                                                             <>^=         + - space       0 at start for filling with 0
         f.tell()→position                [,origin])                                                integer: b binary, c char, d decimal (default), o octal, x or X hexa…
             Very common: opening with a guarded block       with open(…) as f:                                              float: e or E exponential, f or F fixed point, g or G appropriate (default),
             (automatic closing) and reading loop on lines       for line in f :                                             string: s …                                                % percent
             of a text file:                                        # processing ofline                                      ◽ Conversion : s (readable text) or r (literal representation)