Miscellaneous Methods and Techniques

Exponent#

pow(x, y, z=None)
# Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
# Some types, such as ints, are able to use a more efficient algorithm when
# invoked using the three argument form.

Using the 3-argument form is helpful in applications such as cryptography.

Equality vs Identity#

The == operator checks equality whereas is operator checks for identity.

a = [1,2,3]
b = a
b == a # prints True since both list objects look the same

However, using == does not tell us if a and b are pointing to the same object.

a is b # prints True since we assigned b to point to a

Now, we create a new list with the same contents as a.

c = list(a)
a == c # prints True
a is c # prints False

Here, we can see that a and c while containing the same contents, point to two different objects.

As stated in https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python,

  • == is for value equality. Use it when you would like to know if two objects have the same value.
  • is is for reference equality. Use it when you would like to know if two references refer to the same object.

Checking Equality with None#

None is an object. Hence, we should avoid using the equality operator, ==, to compare objects to None. Instead, we use is.

"hello" is None # False
None is None # True

Boolean#

None, 0, and empty strings/lists/dicts/tuples all evaluate to False. All other values are True.

bool(None) # => False
bool(0) # => False
bool("") # => False
bool([]) # => False
bool({}) # => False
bool(()) # => False

Ternary Operator#

'good' if True != False else 'bad'

Reversing a String#

''.join(reversed(string))

String Concatenation#

For concatenating just two strings, the normal + operator is fine.

string = 'hello' + 'world'

For more than two strings, we can perform concatenation more efficiently with the join operator.

string = ''.join([a, b, c]) # a, b and c are strings

Module Imports#

General Module Imports#

import module_name

Importing Functions from a Module#

from module_name import function1, function2, classOne, classTwo

For example, we have a class, Animal, defined in another file, animal.py, we can use them in another file like this:

from animal import Animal

The general format to import functions and class is this:

from "file-name-without-extension" import "function-or-class"

Import All Functions in a Module#

We can import all the functions in a module together. (not recommended)

from module_name import *

Alias for Module Imports#

import module_name as alias_name

Converting from One Type to Another#

Convert Char to ASCII Value#

>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'

Parse String to Decimal (Float/Double)#

x = '2.22'
y = float(x)

Parse String to Integer#

x = '2'
y = int(x) # 2

Finding the Functions in a Module#

import math
dir(math)

__contains__ Operator#

Implementing the __contains__ method will support the containment property in custom classes - usage of in.

Example:

def __contains__(self, item):
return item in self.d

Assuming the above method resides in a custom class called Custom, when an instance is created, we are now able to use the in operator:

x = Custom()
if item in x:
do_smth()

Opening a File#

Examples:

file object = open(file_name [, access_mode][, buffering])
with open(fname) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
# creates a list of the lines read
content = [x.strip() for x in content]
  • Using read, reads the file byte by byte.
  • Using readlines reads file line by line