- Python is not compiled (run directly)
- Python is statically typed (the types of the variables cannot change)
- Python is not strongly typed (do not declare types)
- Python does not use curly braces (use tabs and indentations)
- Boolean values are now
True and False - Logic operator are now
and or - Run pip install on commandline to install packages
- In Google Colab, you can run command line arguments in the Python notebook by prefacing the commands with ! -- e.g. !pip install
- Use \ at the end of a line to indicate continue on the next line
Importing
- Importing library modules
- import math
- from math import sqrt
- import numpy as np
- Importing file as a module
- import homework1 // import homework1 file for the first time
- import importlib; importlib.reload(homework1) // after the first time, use importlib
List
Iteration using enumerate()
Python enumerate(): Simplify Looping With Counters – Real PythonOnce you learn about for loops in Python, you know that using an index to access items in a sequence isn't very Pythonic. So what do you do when you need that index value? In this tutorial, you'll learn all about Python's built-in enumerate(), where it's used, and how you can emulate its behavior.
https://realpython.com/python-enumerate/#using-pythons-enumerate
List comprehensions
Transform list to dictionary or sets



Move a list item to position
l.insert(newindex, l.pop(oldindex))
Dictionary
Dictionary Comprehension
example:
- groceries = {"milk": 2, "egg": 2}
- more_groceries = { k:v*2 for k,v in groceries.items if ....}
https://www.datacamp.com/tutorial/python-dictionary-comprehension
Priority Queue
- Defulat order: non-decreasing
// declare a priority queue
print(q.get()) // dequeue
Strings
Access length
Access charAt(index)
- s[index]
- s[-1] -- counts from the end, so last char of the string
Access substring
- s[1:4] -- from 1 to 3, excluding the end
- s[1:4:2] -- from 1 to 3, but stride 2, i.e. skipping every other character
- s[2:] -- from 2 to end
- s[2:10000] -- from 2 to end
- s[:2] -- from start to 1, excluding the end
- s[:] / s[::] -- copy the entire string
- s[::-1] -- copy and reverse the string
Splitting a string
- s.split(' ') -- split by space (only one space)
Remove spaces
- s.strip() -- removes all spaces (front and back) from a string
Compare strings
- s == 'abc' -- compare values
Converting to string
For loop
for ... in ... :
print();
Specifying range
- range(5) -- 0 to 4, excluding the end
- range(0,5) -- -- 0 to 4, excluding the end
Iterate through elements
- for x in arr // java like for each loop
- for i in range(len(list)) // java like for loop
Iterate through dictionary
- for key, vallue in dict.items()
Iterate through pairs of things
-
for (x, y) in [(a,b) , (c,d)]
Iterator
- A type of objects that have the __iter__() magic method
- Iterator objects can be iterated in for loops
- Throws StopIteration exception when ending
e.g. list, dict, etc.
Create custom iterator class
Usage with handling end of iteration
** same thing happens in a python for each loop
Generators
A special type of function that return a lazy iterator. These are objects that you can loop over like a list.
- basically an iterator, but with less code
- stop and continue execution for each 'yield'
- stores the execution state for future consumption
- returns a generator object
- any function with a yield in the body
How to Use Generators and yield in Python – Real PythonIn this step-by-step tutorial, you'll learn about generators and yielding in Python. You'll create generator functions and generator expressions using multiple Python yield statements. You'll also learn how to build data pipelines that take advantage of these Pythonic tools.
https://realpython.com/introduction-to-python-generators/
Benefits
- Less code than basic iterator
- Memory efficient -- reduces memory usage (it doesn't store a list in memory)
- Good for one-pass summing/counting
- Good for infinite seqence
- Bad for individual values (debugging)
Define a generator function
- e.g. an infinite sequence
Using a generator function
- nums = f() // num is a generator object
- Get next item
- next(nums) OR
- nums.__next__() // using the under-the-hood iterator method
- for i in f(): // keep yielding all the items
Handling the end of an iteration
