Python Notes - ayaohsu/Personal-Resources GitHub Wiki

Data Structure

List

myList.remove("cherry")
del myList[2]    # delete the item at index 2
myList.pop()
myList.pop(5)    # pop the item at index 5
myList = [0] *5
myList.count(3)
myList.remove(6)  # remove the first matching element  
del myList[2]   # delete the element at index 2  
newlist = [x for x in fruits if x != "apple"]

Tuple

myTuple = (1, 5, 10, 15)

faster to initialize and smaller since Python has some optimization

Dictionary

myDict = dict(name="Yao",age=33)
del mydict["age"]
mydict.popitem()    # remove the last inserted item
mydict.keys(), mydict.values()    # view object of keys/values
mydict.update(mydict2)    # overwrite mydict if exists

We can use 'hashable type' as key, such as a tuple, but not a list

Set

myset.discard('a')    # will not throw an error if element does not exist
myset.remove('a')     # will throw an error
set1.union(set2)      # can calculate operations such as union, intersection, difference
set1.issubset(set2)
myset = frozenset([1,2,3])    #immutable set

hashable type

All immutable types are hashable, but not all hashable types are immutable Because hash value for immutable types would not change, so it is hashable For mutable but hashable, we can make it work by defining equality function

String

myStr = """Hello 
World"""
myStr[1:4]   # substring
'ell' in 'hello'    # check substring
mystr.find('c')    # find index of substring/character  
mystr = mystr.strip()    # strip the heading and trailing whitespaces
myStr.upper()
myList = myStr.split()
myStr = ' '.join(myList)

text = "For only {price:,} dollars!".format(price = 123456)    # string format (<var name>: <format>)
text = f"For only {price:,} dollars!"    # f-string

Python strings are immutable (so as integers, doubles, etc.)
Using f-string is faster than format, since it is literal computed on the run time, whereas format requires a function call (and potentially needs to create extra strings)

The StringIO module can be used to read and write strings in the memory buffer.

from io import   
str_io = StringIO()  
strio.write('hello')  
strio.write(' world')   
strio.getvalue()  
'hello world'  

Counter

my_counter = Counter("aaaaabbbc")    # A counter dictionary of character -> occurrences  
my_counter.most_common()    # [ ('a':5) ]; will return a list of tuples

Name Tuple

Point = namedtuple('Point', ['x','y'])
pt = Point(1,-4)
print(pt.x, pt.y)

OrderedDict

Just like a regular dict, but it remembers the order that it was inserted

Deque

from collections import deque
d = deque()
d.append(1)    # 1
d.appendleft(3)    # 3, 1
d.pop()   # pops 1
d.popleft()    # pops 3
d.rotate(1)    # rotate all elements one place to the right   

Concepts

itertools

Itertools provide fast, memory efficient functions used for iterations (in for loops)

for i in count(10)    # infinite iterators; from 10 and count up 
for i in cycle(myList)
accumulate(myList)   # return an itertool object of element accumulate list of myList
permutations(myList,2)   # permutation of all elements with length of 2

Lambda

add10 = lambda x: x + 10

a = [1,2,3,4,5]
b = map(lambda x: x * 2, a)

Usage: you need a simple function and it's only used once. Or you need to pass the function as an argument to another function

Ternary operation

[on_true] if [expression] else [on_false]   

Tool

get time and space

sys.getsizeof()
timeit.timeit()

Modules & Packages

Modular programming: breaking a large, unwieldy programming task into small, separate subtasks.

Three kinds of modules:

  1. A module can be written in Python itself
  2. A module can be written in C and loaded dynamically at run-time
  3. A built-in module contained in the interpreter

Syntax: import ---> still need module name to access objects in the module
from import ---> you can call objects directly (in the global symbol table); only the objects are imported (not the module)

Packages
This allows for a hierarchical structuring of the module namespace using dot notation, to avoid module name collisions. To create a package, you need to use a directory to contain the modules with an init.py file

Syntax:
import pkg.mod1, pkg.mod2
from pkg.mod1 import foo

Random

import random
a = random.uniform(1,10)    # 5.3281649 for example
b = random.randint(1,10)    # random int between 1 to 10   
a = random.choice(myList)    # pick a random element  
random.shuffle(myList)    # shuffle and modify myList
⚠️ **GitHub.com Fallback** ⚠️