Object Comparison


In [4]:
l1 = [23, 68, 34]
l2 = l1
l3 = list(l1)

if l1 == l2 and l1 == l3:
    print("== is not the same objects. it just compares the contents of the Objects.")
if l1 is l2:
    print("is same for assigned objects")
if not l1 is l3:
    print("is not the same for newly created objects")


== is not the same objects. it just compares the contents of the Objects.
is same for assigned objects
is not the same for newly created objects

Printing Dictionaries


In [7]:
d = {1:"One", "two":2, 10:"ten", "all_keys":[1, "two", 10, "all_keys"]}
import pprint
pprint.pprint(d) # prints as objects
import json
json.dumps(d) # prints as a string


{1: 'One', 10: 'ten', 'all_keys': [1, 'two', 10, 'all_keys'], 'two': 2}
Out[7]:
'{"1": "One", "10": "ten", "all_keys": [1, "two", 10, "all_keys"], "two": 2}'

Assertions


In [ ]:
# Syntax 
# result ::= "assert" expression_1 ["," expression_2]
# NEEDS_MORE_EXAMPLES

Copying


In [9]:
# Shallow Copying - only one level deep
l1 = [1, 2, 3]
l2 = list(l1)
if l1[0] is l2[0]:
    print("True, it's only a Shallow Copy!")   
    if not l1 is l2:
        print("Check here!, this proves that the copy worked on element wise and not ion the object in the top level. ")


True, it's only a Shallow Copy!
Check here!, this proves that the copy worked on element wise and not ion the object in the top level. 

In [10]:
# Deep Copying
l1 = [1, 2, 3]
import copy
l2 = copy.deepcopy(l1)
if l1[0] is l2[0]:
    print("True, it may be a shallow Copy!")   
    if not l1 is l2:
        print("Check here!, this proves that the copy worked on element wise and not ion the object in the top level. ")
    else:
        print("Yup it's a deep copy")


True, it may be a shallow Copy!
Check here!, this proves that the copy worked on element wise and not ion the object in the top level. 

Python 3.7.1


In [1]:
# functions

def something(x):
    x = x + 1
    pass

something(1) # seems like nothing is returned from the fucntion, lets check that

print(something(2)) # none value will be returned here


None

In [11]:
import inspect
import dill
# range_decl = inspect.getsource(range)
# range_decl = inspect.getfile(range)
# range_decl = dill.source.getsourcelines(range)
# print(range_decl[0])
print(range.__doc__, "\n", dir(range))
if "__annotations__" in dir(range):
    print(range.__annotations__)


range(stop) -> range object
range(start, stop[, step]) -> range object

Return an object that produces a sequence of integers from start (inclusive)
to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
These are exactly the valid indices for a list of 4 elements.
When step is given, it specifies the increment (or decrement). 
 ['__bool__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index', 'start', 'step', 'stop']

Lists


In [17]:
def operations_on_lists():
    """
    All methods available in lists are implemented as exercises in this function.
    
    method operations available in lists : 11
    They are alphabetically listed below:- 
    
    append
    clear
    copy
    count
    extend
    index
    insert
    pop
    remove
    reverse
    sort
    
    """
    
    sample_list = []
    another_sample_list = []
    
    # append
    print("\n \n Append:")
    sample_list.append(1)
    sample_list.append(2)
    another_sample_list.append(0)
    print(sample_list, another_sample_list)
    
    # clear - this function is similar to del list[:]
    print("\n \n Clear:")
    print(sample_list)
    temp = sample_list # when cleared all objects referencing will be cleared
    sample_list.clear()
    print(sample_list)
    sample_list.append(1)
    sample_list.append(2)
    print(sample_list)
    del sample_list[:]
    print(sample_list)
    
    # copy
    print("\n \n Copy:")
    print(temp)
    sample_list.append(1)
    sample_list.append(2)
    temp = sample_list.copy()
    print(temp)
    
    # count(x) - the number of items x appears in the list
    print("\n \n Count:")
    print(sample_list.count(1))
    sample_list.append(1)
    sample_list.append(1)
    sample_list.append(1)
    sample_list.append(1)
    sample_list.append(1)
    print(sample_list.count(1)) 
    
    # extend - combines two lists into a new list
    print("\n \n Extend:")
    new_list = [1, 2, 4, 9, 16, 25]
    print(new_list)
    new_list.extend([36])
    print(new_list)
    
    # index(x[start, end]) - returns the first location of the item x in the list
    print("\n \n Index:")
    print(sample_list.index(1)) #  returns the start location only
    print(sample_list)
    print(sample_list.index(1, 1)) # find the element 1 in the list starting from the location 1
    
    # insert - an item 'x' at a location i in the list
    print("\n \n Insert:")
    print(sample_list)
    sample_list.insert(0, 2)
    sample_list.insert(len(sample_list), 2)
    print(sample_list)
    
    # Pop - pop the item at location i (or) pops the first item from the list
    print("\n \n Pop:")
    print(sample_list.pop(0))
    print(sample_list)
    print(sample_list.pop())    
    
    # remove(x) - an item 'x' from a the first location the item is found
    print("\n \n Remove:")
    print(sample_list)
    sample_list.remove(2)
    print(sample_list)
    
    # reverse
    print("\n \n Reverse:")
    another_sample_list.append(10)
    another_sample_list.append(100)
    another_sample_list.append(1000)
    print(another_sample_list)
    another_sample_list.reverse()
    print(another_sample_list)
    
    # Sort(key=None, reverse=False)
    print("\n \n Sort:")
    print(another_sample_list)
    another_sample_list.sort()
    print(another_sample_list)
    another_sample_list.sort(reverse=True)
    print(another_sample_list)
    
    return None
    
operations_on_lists()


 
 Append:
[1, 2] [0]

 
 Clear:
[1, 2]
[]
[1, 2]
[]

 
 Copy:
[]
[1, 2]

 
 Count:
1
6

 
 Extend:
[1, 2, 4, 9, 16, 25]
[1, 2, 4, 9, 16, 25, 36]

 
 Index:
0
[1, 2, 1, 1, 1, 1, 1]
2

 
 Insert:
[1, 2, 1, 1, 1, 1, 1]
[2, 1, 2, 1, 1, 1, 1, 1, 2]

 
 Pop:
2
[1, 2, 1, 1, 1, 1, 1, 2]
2

 
 Remove:
[1, 2, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1]

 
 Reverse:
[0, 10, 100, 1000]
[1000, 100, 10, 0]

 
 Sort:
[1000, 100, 10, 0]
[0, 10, 100, 1000]
[1000, 100, 10, 0]

Tuples and Sequences


In [27]:
# example 1, 2, 3, 4
# All declarations example
print("\n Sequences Example:")
tuple_sample = 1, 3, "Something else"
another_tuple_sample = ("this", "works", "too")
sequence_sample = None # usually the sequence types are - list, tuple, range
# Mind a set is not a sequence
set_sample = {"apple", "banana", "capricum"} # Check this - it is similar to tuple or the same
dictionary_sample = {"Key_1": "Value_1"}
list_sample = ["Something"]

print(type(tuple_sample), type(another_tuple_sample), 
      type(sequence_sample), type(set_sample),
      type(dictionary_sample), type(list_sample))

# example 5 - How to identify an object individually in Python
# this is done to chekc the mutability of objects in Python
print("\n Mutability Verification:")
print(id(tuple_sample))
tuple_sample = "new_tuple"
print(id(tuple_sample))
print(id(list_sample))
list_sample[0] = "new_list-item"
print(id(list_sample))
# So tuples are immuatble while lists are mutable

# example 6  - enumerate example
print("\n Enumerate Example:")
for i, obj in enumerate(another_tuple_sample):
    print(i, obj)
    
# exampel 7 - zip functionality, mind the length of both objects to be zipped
print("\n Zip Example:")
for i, obj in zip(another_tuple_sample, another_tuple_sample):
    print(i, obj)

# example 8 , 9- reversed and sorted
print("\n Reversed and Sorted:")
temp = list(set_sample)
print(temp)
print([x for x in reversed(temp)])
print(sorted(temp))

# example 10 - comparing the sequences
# lexicographical ordering is used
print("\n Comparing Sequences :")
print((1, 2, 3) == (1, 2, 3))
print((1, 2, 3) == (1, 2, 3, 4))
print((1, 2, 3) < (1, 2, 3))
print((1, 2, 3) <= (1, 2, 3))


 Sequences Example:
<class 'tuple'> <class 'tuple'> <class 'NoneType'> <class 'set'> <class 'dict'> <class 'list'>

 Mutability Verification:
2488879858816
2488879928368
2488880743944
2488880743944

 Enumerate Example:
0 this
1 works
2 too

 Zip Example:
this this
works works
too too

 Reversed and Sorted:
['capricum', 'apple', 'banana']
['banana', 'apple', 'capricum']
['apple', 'banana', 'capricum']

 Comparing Sequences :
True
False
False
True

Modules


In [9]:
# Example 1 to 7 - Creating, calling, assigning it to a local variable
def modules():
    '''
    Function with examples describing the uses of a module.
    
    What is a module?
        A module is a file containing Python definitions and statements.
    
    So any functions within a module can be accessed, by the file name.
    For example, lets create a file called fibo.py and write a function in it
    to calculate the fibonocii sequence of a given number n and import that
    function here inside this function. 
    '''
    # example 1
    import fibo
    # example 2
    fibo.fibonocii(10) 
    # example 3
    fib = fibo.fibonocii 
    fib(10)
    
    # Note 1:
    # Any changes in the module code after importing it, cannot be
    # reflected in the kernel right away. Restart the kernel for the updates. 
    
    # example 4
    from fibo import fibonocii
    # example 5
    # from fibo import *  -- NOT Working Check this code
    # example 6
    import fibo as fibonocii
    fibonocii.fibonocii(10)
    # example 7
    fibonocii = None
    from fibo import fibonocii as fib
    fib(10)
    
    # NOTE 2:
    # Compiled modules are stored in __pycache__ location creating a .pyc file
    
    # example 8
    import builtins # allows us to find all the functions in a module easily
    print(dir(builtins))
    
    # example 9, 10 - TODO Test the declaration or importing without using 
    # the module name from the package
    from textpackage import something
    something.print_something()
    pass

modules()


[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
Something

Input & Output

Formatting


In [ ]:

Reading and Writing Files


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [2]:
for i in range(5):
        print(i)


0
1
2
3
4

Yet to master the following:


In [ ]:
# annotations with examples
# shallow vs. deep copy with examples
# tuples vs. sequences with examples - Done