Lists Tuples
Python 3 Cheat Sheet Ordered sequence of elements of arbitrary data types. Immutable list of values.
(Version 1) Create empty empty_l = []
Create empty t = ()
Create example l = ['zero', 1, 2.0, 3 + 0j]
Create with one element t = 123, # Trailing comma
Retrieve item (idx from 0) d[2] # Returns 2.0
Basic data types and introspection Create example / packing t = 123, 'abc', 1+5j
Change item l[2] = 'two_point_o' # Optional with parenthesis
Basic native data types: Query length len(l) # Returns 4 t = (123, 'abc', 1+5j)
Append value to the end [Link](4) Unpacking u, v, w = t
Integer i = 42 Extend by another list. [Link]([5, 5]) Unpacking some entries u, _, w = t
Float 3.14159 # appearances of item. [Link](5) # Returns 2
Complex number 2 + 3j
Looping through all items: Functions
Boolean b = True for it in l:
String s = 'spam' # do something... Simple function:
None type. n = None def hello():
print("Hello!")
Introspection functions: Slicing lists
Function with arguments and a return value:
a = ['a', 'b', 'c', 'd', 'e'] def add(a, b):
Type of an object type(var)
return a + b
Built-in system help help(var)
Lists objetc’s attributes dir(var) Function with a default argument that has multiple return
Class membership test isinstance(var, class) values as a tuple:
def f(a, b, c=0):
Syntax [start:end] (start - incl., end - excl., step=1) return a + c, b + c
Operators Explicit start/end a[2:4] # ['c','d']
Arithmetic operators: Implicit end (incl.) a[2:] # ['c','d','e'] Conditional Statements
Implicit start a[:3] # ['a','d','e'] Conditional tests:
Addition x + y Negactive indices a[1:-1] # ['b','c','d']
Subtraction x - y equal / not equal x == 25 , x != 25
Floating point division x / y Syntax [start:end:step] greater / smaller than x > 25 , x < 25
Integer division x // y Explicit start/end/step a[1:5:2] # ['b','d'] greater /smaller or equal to x >= 25 , x <= 25
Multiplication x * y Negative step - backwards a[4:1:-2] # ['e','d','c']
Exponentiation x ** y Implicit start/end/step=1 a[::] # ['a','b','c','d','e'] If statement:
No valid index in range a[4:2:1] # [] if x >= 0:
Boolean operators: print("Non-negative")
And x and y Dictionaries If-elif-else statement:
if x < 0:
Or x or y Mapping of key-value pairs. print("Negative")
Negation not x Create empty empty_d = {} elif x == 0:
Create example d = {'name': 'Alice', 'age': 25} print("Zero")
else:
Printing and strings Retrieve entry d['age'] # Returns 25
print("Positive")
Add / change entry d['city'] = 'Lausanne'
Simple print statement:
print("Hello!") Delete entry del d['age']
Delete all entries [Link]() Loops
String formatting: Test if key exists 'name' in d # Returns True Use for to iterate over lists:
Number of entries len(d) for x in [1, 2, 3]:
Integers "int: %d" % 5 print(x)
Floats "float: %f" % 3.14 Looping through all key-value pairs:
Strings "str: %s" % "foo"
for key, val in [Link](): Otherwise, use while loops:
# do something.. i = 0
Multiple values via tuples "two ints: %d %d" % (1, 2) Similarly, access all keys or values as: while i < 3:
[Link]() print(x)
Cheat-sheet by J. Bednarik and T. Zeltner ([[Link]|[Link]]@[Link]). [Link]() i += 1
LATEX template by Michelle Cristina de Sousa Baltazar.
List comprehensions
Syntax:
[expr(v) for v in some list (if predicate(v))]
Get powers of 2 : [20 , 210 ]:
l = [2**x for x in range(11)]
# [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
Get extension-less names of files with ”jpg”extension:
files = ['[Link]', '[Link]', '[Link]']
l = [f[:-4] for f in files if f[-4:] == '.JPG']
# ['img1', 'img3']
Importing modules
Import entire module:
>>> import math
>>> [Link](2)
1.4142135623730951
Import specific functions:
>>> from math import sqrt
>>> sqrt(2)
1.4142135623730951
Giving a module (or functions) an alias:
>>> import math as m
>>> [Link](2)
1.4142135623730951
Importing all functions from a module:
(Don’t do this! It can result in naming conflicts.)
>>> from math import *