Here are all the import Python language features you need to know.
These are all the built-in data structure types in Python:
# primitives
x = 1 # integer
x = 1.2 # float
x = True # bool
x = None # null
x = float('inf') # infinity (float)
# objects
x = [1, 2, 3] # array or "list"
x = (1, 2, 3) # tuple
x = {"hi": 2} # hashmap or "dict"
x = {1, 2, 3} # set
x = "abc123" # strYou can convert between types by wrapping them in a cast, like this:
n = 7
str(n) # '7'
int('7') # 7
x = [1,2,3]
set(x) # {1,2,3}
tuple(x) # (1,2,3)
s = {1,2,3}
list(s) # [3,1,2], sets don't store orderHere are very basic operations that you should know:
# set up variables for the example
a = [1]
b = [1]
a == b # True, compares value
a is b # False, compares memory location
1 / 2 # .5, division
1 % 2 # 1, remainder
1 // 2 # 0, division rounding down
2 ** 5 # 32, power 2^5You can conditionally set a value using if statement, called a "Ternary Operator".
# gives 0 if x is equal to 5, else gives 1
y = (0 if x == 5 else 1)You can set multiple variables at the same time. This is particularly useful when you want to swap variables with each other. Here are a few examples (this is called "object destructuring" in general):
# sets a=b, b=a (swap a and b) - this is treated as: (a,b) = (b,a)
a, b = b, a
# sets a=1, b=2
a, b = 1, 2
# sets a=1, b=2, c=3, d=4, e=[5, 6]
[a, b, [c, d], e] = [1, 2, [3, 4], [5, 6]]for i in range(4):
# 0 1 2 3
for i in range(1, 4):
# 1 2 3
for i in range(1, 6, 2): # loop in steps of 2
# 1 3 5
for i in range(3, -1, -1): # loop backwards
# 3 2 1 0
arr = ["a", "b"]
for x in arr:
# "a" "b"
hmap = {"a": 4, "b": 5}
for x in hmap:
# "a" "b"
x = 0
while x != 4:
# 0, 1, 2, 3
x += 1
x = 4
if x == 4:
print('This prints')
elif x == 5:
print('This does not print')
elif x == 6:
print('This does not print')
else:
print('This does not print')Python has nice syntax for creating arrays. Here's an example that shows the general logic you can use (this is called a "List Comprehension"):
# This creates an array:
x = [a*b for a in A for b in B if a > 5]
# The code above is equivalent to:
x = []
for a in A:
for b in B:
if a > 5:
x.append(a*b)Here are some more examples:
x = [2*n for n in range(4)]
# [0, 2, 4, 6]
x = [a for a in [1,2,3,4,5,6] if a % 2 == 0]
# [2, 4, 6]
# 2 x 3 matrix of zeros
x = [[0 for col in range(3)] for row in range(2)]
# [[0, 0, 0],
# [0, 0, 0]]Generator Comprehensions are the same as List Comprehensions, except they generate values lazily and can stop early. To do a generator comprehension, just use () instead of [].
# does not run yet
computations = (i for i in range(5))
# runs the loop, might stop early
for x in computations:
# ...Note that () can mean a tuple, or it can mean a generator depending on context.
To create a function, you use the def keyword:
def my_function():
# do things here
my_function() # runs the code in the functionAll variables declared inside a function are local. You need to use the nonlocal keyword if you want to use variables that appear outside of a function. Here's an example:
x = 1
y = 1
def fn():
nonlocal x # declares x as nonlocal
x = 2 # sets `x` that appears outside of the function
y = 2 # sets `y` as a new local variable
fn()
print(x) # 2
print(y) # 1You only have to worry about using nonlocal with primitive types like with numbers. This is because objects are automatically globally scoped. See below for details.
x = [1]
y = [1]
def fn():
nonlocal x
x[0] = 2
y[0] = 2 # this would normally give an error. to avoid this, python refers to a more globally scoped variable, so `nonlocal` is not needed
fn()
print(x) # [2]
print(y) # [2]You can also declare a function in-line, using the keyword lambda. You don't have to do this, it's just for convenience. The following 2 functions are the same:
def fn(x,y):
return x + y
lambda x,y: x + yAnything can be used as a boolean. Values of None, 0, and empty data structures like [] evaluate to False, and everything else evaluates to True.
a = None
if a: # does not run
print('does not print')
b = []
if b: # does not run
print('does not print')
c = [15]
if c: # runs
print('prints')The any() function check if any value is true, and the all() function checks if all values are true.
any([True, False, False]) # True
all([True, False, False]) # FalseStrings come with the useful built-in functions .split(x), .join(x), ord(x), and chr(x).
x = 'a:b:c'
x.split(':') # ['a', 'b', 'c']
x = ['a', 'b', 'c']
':'.join(x) # 'a:b:c'
# convert between character and unicode number
ord("a") # 97
chr(97) # 'a'To write an expression over multiple lines, you can escape newlines with \, or you can wrap the expression in parentheses.
# escape newlines
x = 5 \
+ 10 \
+ 6
# wrap in parentheses
x = (
5
+ 10
+ 6
)You can select parts of an array or string very easily, called "splicing". Specify the start index, end index, and/or step size that you want to make, and it will give you a new array. Here are some examples:
# splice array using x[start:end:step]
x = [0,1,2,3,4]
x[2:] # [2,3,4]
x[:2] # [0,1]
x[1:4] # [1,2,3]
x[3::-1] # [3,2,1,0]
x[-1] # 4Almost everything in Python is a pointer. Whenever you write A=B, Python points A to B. See Pointers for more.
Here's a reference to the offical Python docs: https://docs.python.org/3/library/index.html. The Built-in Functions and Built-in Types sections are the most useful parts to skim, although it's totally optional reading. The docs are not formatted in a very readable way.