Disclaimer: These are my notes, hence focused on the areas which I am prone to forget. There is a strong possibility of some sections not making sense to you or they are too easy for you.
Built in Data Structures, Functions and Files
Tuple
Important Points:
- Immutable
- Can store mutable objects, which can be modified inplace
+
operation results in new concatenated tuple*
operation as in list, results in concatenating that many copies of tuples
(1, 2, [3, 4], True)
[3, 4]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-d14146d6c2a7> in <module>()
----> 1 tup[1] = 5
TypeError: 'tuple' object does not support item assignment
(1, 2, [3, 4, 67], True)
(1, 2, [3, 4, 67], True, 45, 87)
(1, 2, [3, 4, 67], True, 1, 2, [3, 4, 67], True, 1, 2, [3, 4, 67], True, 1, 2, [3, 4, 67], True, 1, 2, [3, 4, 67], True)
Unpacking Uses
- Swapping
- In loops
- Filtering partial elements and neglecting rest.
unpacking
1
2
swapping
2
1
nested tuple unpacking
1 2 3 5
loops
a 1
b 2
a 3
b 5
filtering rest
1
rest: [(3, 5)]
Tuple methods
It is light on instance method, one useful is count(element)
, which counts the number of occurrences of the element in tuple.
4
List
Important Points
insert
method allows you to insert elements at any index but it is costly operation because some indexes need to be shifted. Insertion index must be between 0 and lenght of the list inclusive.pop
is opposite ofinsert
. It removes and returns the value at particular index.- Elements can be removed by value with
remove
method. - Checking if a element is in list by using
in
keyword is expensive operations because it is a linear search. Set and Dictionaries uses hash table and hence takes constant time for retrieval. - Concatenating two list is possible using
+
orextend
method. Addition operation is little costly because new objects needs to be created. - Sorting is possible using method
sort
and functionsorted
both taking same arguments. It can also take an argumentkey
, a function which returns a number to sort on. - You can mainatain a binary search tree using
bisect
type frombisect
module. - In slicing, integer after the second colon represents a step.
a[::2]
will produce another list starting from first element ofa
and stepping single element till end. Negative number in slicing represents count from end of the list, i.e,a[-1]
represents last element of the list. If we combine stepping with this, we can reverse the list very easily bya[::-1]
.
`insert` method allows you to insert elements at any index but it is costly operation because some indexes need to be shifted. Insertion index must be between 0 and lenght of the list inclusive.
[1, 2, 3, 4, 5]
[1, 89, 2, 3, 4, 5]
`pop` is opposite of `insert`. It removes and returns the value at particular index.
poped element 89
[1, 2, 3, 4, 5]
Elements can be removed by value with `remove` method.
[1, 2, 4, 5]
Checking if a element is in list by using `in` keyword is expensive operationsbecause it is a linear search.
False
Concatenating two list is possible using `+` or `extend` method. Addition operation is little costlybecause new objects needs to be created.
[1, 2, 4, 5, 7, 8, 9]
[1, 2, 4, 5]
[1, 2, 4, 5, 7, 8, 9]
Sorting is possible using method `sort` and function `sorted` both taking same arguments. It can also take an argument `key`, a function which returns a number to sort on.
['one', 'three', 'two']
['three', 'one', 'two']
Functions on List/Sequence
enumerate
: Returns sequence of (i, element_i) i being the unique integer index and element_i being the member of the squence.
zip
: Merges multiple seqences to create sequence of tuples. Can accept any arbitory number of elements in sequence, the pairing will happen according to shortest of sequence. Unzipping is also possible which is actualy convering list of rows to list of columns.
sorted
: same as sort method.
reversed
: gives a generator which yield the sequence in reverse order
Returns sequence of (i, element_i) i being the unique integer index and element_i being the member of the squence.
<enumerate object at 0x7f3e60320cf0>
Merge two lists
[('a', 7), ('b', 3), ('c', 9), ('d', 0)]
Converting to list of firstnames and lastnames. Isn't that clever?
[('Elon', 'Bill'), ('Musk', 'Gates')]
Dictionary
Important properties
- Access time is always constant.
- Methods
keys
andvalues
gives iterator on keys and values of the dictionary respectively. Though, there is no particular order in dictionary, these method gives output in order. - zip can help you in creating dictionary from sequence of keys and values.
a.get(name, default_value)
will get you value of keyname
if it exists in dictionary a,default_value
otherwise. Ifdefault_value
not given,None
will be returned.- Sometimes, you might need to check if the key exists in the dictionary, set some default value to it if it does not exists, and then update the same value.
a.setdefault('key_name', default_value)
can be used for this. collections
module hasdefaultdict
, which makes this task way simpler.- Keys of the dictionary need to be hashable objects. scalars
int
,float
,strings
or tuples with its objects hashable. All immutable object in python are hashable.
zip can help you in creating dictionary from sequence of keys and values.
{0: 4, 1: 3, 2: 2, 3: 1, 4: 0}
a.get(name, default_value) will get you value of key name if it exists in dictionary a, default_value otherwise. If defaul_value not given, None will be returned.
0
{'K': ['Keys'], 'o': ['of', 'objects.', 'or', 'objects', 'object'], 't': ['the', 'to', 'tuples'], 'd': ['dictionary'], 'n': ['need'], 'b': ['be'], 'h': ['hashable', 'hashable.', 'hashable'], 's': ['scalars', 'strings'], 'i': ['int,', 'its', 'immutable', 'in'], 'f': ['float,'], 'w': ['with'], 'A': ['All'], 'p': ['python'], 'a': ['are']}
Keys of the dictionary need to be hashable objects. scalars int, float, strings or tuples with its objects hashable. All immutable object in python are hashable.
dict_keys(['K', 'o', 't', 'd', 'n', 'b', 'h', 's', 'i', 'f', 'w', 'A', 'p', 'a'])
dict_values([['Keys'], ['of', 'objects.', 'or', 'objects', 'object'], ['the', 'to', 'tuples'], ['dictionary'], ['need'], ['be'], ['hashable', 'hashable.', 'hashable'], ['scalars', 'strings'], ['int,', 'its', 'immutable', 'in'], ['float,'], ['with'], ['All'], ['python'], ['are']])
Set
Important Points
- Set support set operations like union, intersection, difference, disjoint.
- Every logical set operation has, inplace counterpart.\
Comprehensions
Normal list coprehensions [expr for val in collection if condition]
[9, 5]
Nested list comprehensions are little hard to wrap your head around. If you feel stucked, don’t bother writing the normal nested loops. In fact, normal nested loops can help you to write the nested list comprehension because the order of the loops is same in both, with the condition at last as usual.
['Shooteron', 'Gully', 'Kiska', 'tumko', 'intazaar', 'says,', 'fools', 'makes', 'stars', "they're", 'shining']
['Shooteron', 'Gully', 'Kiska', 'tumko', 'intazaar', 'says,', 'fools', 'makes', 'stars', "they're", 'shining']
Functions
Important Points
- positional arguments before keyword arguments
- Unlike functions defined by
def
, lambda functions don’t get the automatic assignment to the__name__
attribute, hence they are called anonymous functions. - Currying is a fancy computer science term used for partial argument functions. It can be done using
lambda
functions orpartial
fromfunctools
module.
Value in __name__ attrubute of function defined by def: adder
Value in __name__ attribute in lambda function: <lambda>
With partial: 11
With lambda: 11
Generators
The iterator protocol is a way to make objects iterable. An iterator is an object which will yield objects to the python interpreter when used in a context like for
loop. Most method which expects list like arguments, also takes iterable object. Generator is a concise way to construct new iterable object.
Important Points
- generator expressions can be generated using comprehension enclosed in round breckets
- To build a generator you need a function with
yield
instead ofreturn
- Module
itertools
has nice functions to work on generators or any other sequences in python.groupby
,combinations
,permutations
to name few.groupby
can help you in grouping consecative elements in sequence from the given list or generator with respect to a key function
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
4 ['Elon', 'Bill', 'Lina']
5 ['Bruno']
4 ['Wong']
5 ['Jonas']
8 ['Priyanka']
Exception Handling
Important Point
- In iPython you can set the detail level of an exception by using
%xmod Verbose
. To revert it back%xmod Plain
.
Close any resource if it is open.
Failed
Close any resource if it is open.
Files
Important points
- if you read a file with function
open
, you can use the file handel to iterate over lines in the file as a string. Each line will have theEOL
line character which can be stripped using methodrstrip
orstrip
. - To read a binary file you can attach
b
to file read moder
. File read inrb
mode will read a byte as a character. - Method
read
, takes the number of characters to read and returns them and advances the file handle position. - Method
tell
will give you the current position of the file handle. - Method
seek
will seek the file handle by give number of the integer argument. It also returns the same number. - You can check the default encoding from
sys.getdefaultencoding
x
write mode. Raises error if the file already exists.r+
read and write.- You can write lines in a list to a file using method
writelines
- By default, python will read files in text mode, i.e, in Unicode encoding.
['if you read a file with function open, you can use the file handel to iterate over lines in the file as a string. Each line will have the EOL line character which can be stripped using method rstrip or strip.', 'To read a binary file you can attach b to file read mode r. File read in rb mode will read a byte as a character.', 'Method read, takes the number of characters to read and returns them and advances the file handle position.', 'Method tell will give you the current position of the file handle.', 'Method seek will seek the file handle by give number of the integer argument. It also returns the same number.', 'You can check the default encoding from sys.getdefaultencoding', 'x write mode. Raises error if the file already exists.']
utf-8