Miscellaneous Methods and Techniques
#
ExponentUsing the 3-argument form is helpful in applications such as cryptography.
#
Equality vs IdentityThe ==
operator checks equality whereas is
operator checks for identity.
However, using ==
does not tell us if a and b are pointing to the same object.
Now, we create a new list with the same contents as a.
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 NoneNone
is an object. Hence, we should avoid using the equality operator, ==
, to compare objects to None
. Instead, we use is
.
#
BooleanNone, 0, and empty strings/lists/dicts/tuples all evaluate to False. All other values are True.
#
Ternary Operator#
Reversing a String#
String ConcatenationFor concatenating just two strings, the normal +
operator is fine.
For more than two strings, we can perform concatenation more efficiently with the join
operator.
#
Module Imports#
General Module Imports#
Importing Functions from a ModuleFor example, we have a class, Animal
, defined in another file, animal.py
, we can use them in another file like this:
The general format to import functions and class is this:
#
Import All Functions in a ModuleWe can import all the functions in a module together. (not recommended)
#
Alias for Module Imports#
Converting from One Type to Another#
Convert Char to ASCII Value#
Parse String to Decimal (Float/Double)#
Parse String to Integer#
Finding the Functions in a Module__contains__
Operator#
Implementing the __contains__
method will support the containment property in custom classes - usage of in
.
Example:
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:
#
Opening a FileExamples:
- Using
read
, reads the file byte by byte. - Using
readlines
reads file line by line