Skip to content

Instantly share code, notes, and snippets.

@EddiG
Last active May 3, 2021 11:46
Show Gist options
  • Save EddiG/0916260622b83a05440f170f672e4658 to your computer and use it in GitHub Desktop.
Save EddiG/0916260622b83a05440f170f672e4658 to your computer and use it in GitHub Desktop.
Cheatsheet of Python 3

Python 3

Discovery helpers

Getting a description about some of the classes or functions
help(tuple)
help(tuple.count)
Getting attributes of object
dir(tuple)
# or
dir((1,))
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
# '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', 
# '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
# '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
Getting type
type('a string')
# <class 'str'>
type(33)
# <class 'int'>

Numerics

  • int
  • float
  • complex

Type 'int'

Instantiate
int(15)
int(15.34)
# will returns 15

int('15')
int('0x0f', 16)
int('0b1111', 2)
# will parse to 15

int('0x0f', 0)
int('0b1111', 0)
# will parse to 15
# the difference in that it allows any type of value notation
int('0x0f')
# will cause the ValueError: invalid literal for int() with base 10: '0x0f'
Before parsing string
'5'.isdecimal()
# True
# Use it for testing that the string can be parsed to int

'½'.isnumeric()
# True
# Don't use it

'³'.isdigit()
# True
# Don't use it

Sequences

  • list (muttable)
  • tuple (immuttable)
  • range (immutable)

Type 'list'

a = [1, 2, 3]

a[1]
# 2

a[-1]
# 3

len(a)
# 3
Slicing
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

# the general form is a[start:end:step]
# where, by default, start = 0, end = the size of list, step = 1

a[4:]
# [5, 6, 7, 8, 9, 0]
# will return all elements from the index 4 (inclusive)

a[:4]
# [1, 2, 3, 4]
# will return all elements from 0 (inclusive) to 4 (exclusive)

a[4:5]
# [5]
# will return elements from 4 (inclusive) to 5 (exclusive)

a[0:10:2]
a[:10:2]
a[::2]
# [1,3,5,7,9]
# will return elements placed in even position

b = a[:]
# in 'b' will be the copy of 'a' list
# so the 'a is b' returns 'False' because the 'b' is a new instance of type 'list'
# but the 'a == b' returns 'True' because the values of the list are equal
a = [1,2,5,6]
a[2:4] = [3,4]
print(a)
# [1,2,3,4]
import numpy as np
A = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(A)
[[1 2 3]
 [4 5 6]
 [7 8 9]]
 
# from each row take first column
print(A[:,0])
[1 4 7]

# from the orginal array take top left square array of 2x2 elements
print(A[:2,:2])
[[1 2]
 [4 5]]
 
 # from the orginal array take bottom right square array of 2x2 elements
 print(A[1:,1:])
 [[5 6]
  [8 9]]
  
# reshape 1x3 array into 3x1
A1 = A[:,0] # first column
print(A1.reshape(len(A1), 1))
[[1]
 [4]
 [7]]
Comprehension
exist_ids = [1,4,5,8]
received_ids = [4,3,7]
new_ids = [id for id in received_ids if id not in exist_ids]
# or preferred notation for complex case
new_ids = [
  id
  for id in received_ids
  if id not in exist_ids
]
print(new_ids)
# [3, 7]

prices = [12, 45, 10]
prices_with_tax = [price + price * 0.5 for price in prices]
print(prices_with_tax)
# [18.0, 67.5, 15.0]

Type 'tuple'

a = (1, 2, 'a string')
# or
a = 1, 2, 'a string'
print(a)
# (1, 2, 'a string')
a = (1, 2, 3)
b = (4, 5, 6)
print(a + b)
# will output '(1, 2, 3, 4, 5, 6)'
(1,1,2,1).count(1)
# 3

Mapping Types

  • dict

Type 'dict'

Constructing

a = dict('Bob' = 22, 'Jhon' = 33)
a = { 'Bob': 22, 'Jhon': 33 }
a = dict(zip(['Bob', 'Jhon'], [22, 33]))
a = dict([('Bob', 22), ('Jhon', 33)])
a = dict({ 'Bob': 22, 'Jhon': 33 })

print(a)
# { 'Bob': 22, 'Jhon': 33 }

Accessing

a = { 'Bob': 10, 'Mike': 12 }

a['Bob']
# 10
a['Kate']
# KeyError: 'Kate'

a.get('Bob', 'Not found')
# 10
a.get('Kate', 'Not found')
# Not found

'Kate' not in a
# True

Updating

a = {'Bob': 10, 'Mike': 11}
a.update({'Kate': 10, 'Bob': 9})
print(a)
# {'Bob': 9, 'Mike': 11, 'Kate': 10}

Iterating

a = {'Bob': 10, 'Mike': 11}

for key in a: print(key)
# Bob
# Mike

for key, value in a.items(): print(key, value)
# Bob 10
# Mike 11

Deleting

a = {'Bob': 10, 'Mike': 11}
del a['Bob']
print(a)
# {'Mike': 11}

Set Types

  • set (mutable)
  • frozenset (immutable)

Type 'set'

a = set((1,2,3,2,1))
a = {1,2,3,2,1}
print(a)
# { 1, 2, 3 }
# will return only unique values
# subset
{1,2,3} < {1,2,3}
# False
{1,2,3} < {1,2,3,4}
# True
{1,2,3} <= {1,2,3}
{1,2,3}.issubset({1,2,3})
# True

# superset
{1,2,3} > {1,2,3}
# False
{1,2,3,4} > {1,2,3}
# True
{1,2,3} >= {1,2,3}
{1,2,3}.issuperser({1,2,3})
# True

# union
{1,2,3} | {0,4,5}
{1,2,3}.union({0,4,5})
# {0, 1, 2, 3, 4, 5}

# intersection
{1,2,3} & {4,5,1,2}
{1,2,3}.intersection({4,5,1,2})
# {1, 2}

# difference
{1,2,3} - {1,2,4,5}
{1,2,3}.difference({1,2,4,5})
# {3}

# symmetric difference
{1,2,3} ^ {1,2,4,5}
{1,2,3}.symmetric_difference({1,2,4,5})
# {3, 4, 5}

Text Sequence

  • str

Type 'str'

msg = 'Hello world'
msg = "Hello world"
msg = 'Hello %s' % 'world'
msg = '%s %s' % ('Hello', 'world')
msg = '{0} {1}'.format('Hello', 'world')

msg = """Hello
world"""
print(msg)
# 'Hello\nworld'
Remove extra spaces (also applicable for any chars)
' '.join('   Hello     world '.split())
# will return 'Hello world'

Comparisons

True and False
# False
True or False
# True
True and not False
# True

(1,2,3) == (1,2,3)
# True
(1,2,3) < (1,2,4)
# True

(1,2,3) is (1,2,3)
# False
(1,2,3) is not (1,2,3)
# True

a = 11
b = 11
a is b
# True
# because of 'id(a) == id(b)' is True

isinstance(2, int)
# True
isinstance('a string', str)
# True

2 in (1,2,3)
# True
5 in (1,2,3)
# False

'name' in {'id': 1, 'name': 'Jhon'}
# True
'age' not in {'id': 1, 'name': 'Jhon'}
# True

Scope

def local():
    i = 'local'

    def another():
        i = 'another'

    def nonlocal_var():
        nonlocal i
        i = 'nonlocal'
    
    def global_var():
        global i
        i = 'global'
    
    print(i)
    # local

    another()
    print(i)
    #local

    nonlocal_var()
    print(i)
    # nonlocal

    global_var()
    print(i)
    # nonlocal
    

local()
print(i)
# global

Exceptions

try:
  print(int('foo'))
except ValueError as e:
  print('You must enter a valid number')
except Exception as e:
  print('Something went wrong')

Functions

def foo(a, b = 2, c = 3):
  """ Return a sum of arguments """
  return a + b + c

print(foo(1))
# 6

print(foo(1, c = 5))
# 8

Classes

class Pet:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def greeting(self, owner):
        print('Hello {1}!'.format(owner))

class Cat(Pet):
    def greeting(self, owner):
        print('Miau! Hello {0}! My name is {1} and I\'m {2} cat'.format(owner, self.name, self.color))

cat = Cat('Kiti', 'brown')
cat.greeting('Mike')

Modules

# discount.py
__discount__ = 0.1

def price_with_discount(price):
  return price - price * __discount__

def discount(price):
  return price * __discount__

# How to verify that the module executed from the CLI
if __name__ == '__main__':
  import sys
  print(discount(int(sys.argv[1])))
# app.py
import discount

print(discount.price_with_discount(100))
# 90.0
# app.py
from discount import discount, price_with_discount

print(price_with_discount(100))
# 90.0

print(discount(100))
# 10.0
python3 discount.py 100
10.0

Files

f = open('goods.csv', 'r')

for line in f:
  print(line)
# book,100
# doll,5
# car,10

# don't forget to close file or use prefer way described below
f.close()
# it will close the file after leaving a 'with' scope
with open('goods.csv', 'r') as f:
  for line in f:
  print(line)
# book,100
# doll,5
# car,10

Parsers

CSV

book,100
doll,34
car,23
import csv

with open('goods.csv', 'r') as f:
    goods = csv.reader(f)
    for item in goods:
        print('{0}: {1}'.format(item[0], item[1]))
# book: 100
# doll: 34
# car: 23

JSON

[
  {
    "name": "book",
    "quantity": 100
  },
  {
    "name": "doll",
    "quantity": 34
  },
  {
    "name": "car",
    "quantity": 23
  }
]
import json

with open('goods.json', 'r') as f:
    goods = json.load(f)
    for item in goods:
        print('{0}: {1}'.format(item['name'], item['quantity']))
# book: 100
# doll: 34
# car: 23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment