map()


In [26]:
def fahrenheit(T):
    return (9.0/5)*T + 32

In [27]:
fahrenheit(0)


Out[27]:
32.0

In [28]:
temp = [0, 22, 52, 79, 100]

In [29]:
map(fahrenheit, temp)


Out[29]:
[32.0, 71.6, 125.60000000000001, 174.20000000000002, 212.0]

In [30]:
map(lambda T: (9.0/5)*T + 32, temp)


Out[30]:
[32.0, 71.6, 125.60000000000001, 174.20000000000002, 212.0]

In [31]:
lambda x,y: x+y


Out[31]:
<function __main__.<lambda>>

In [32]:
a = [1,2,3]
b = [4,5,6]
c = [7,8,9]

In [33]:
map(lambda x,y:x+y, a, b)


Out[33]:
[5, 7, 9]

In [34]:
map(lambda x,y,z: x+y+z, a,b,c)


Out[34]:
[12, 15, 18]

In [35]:
map(lambda x:x*-1, a)


Out[35]:
[-1, -2, -3]

reduce()


In [36]:
m_list = [12,56,79,45]

In [37]:
reduce(lambda x,y:x+y, m_list)


Out[37]:
192

In [38]:
max(m_list)


Out[38]:
79

In [39]:
find_max = lambda x,y: x if x > y else y

In [40]:
reduce(find_max, m_list)


Out[40]:
79

In [41]:
m_list2 = ['a', 'z', 'c', 'g']

In [42]:
max(m_list2)


Out[42]:
'z'

In [43]:
reduce(find_max, m_list2)


Out[43]:
'z'

In [44]:
m_list3 = ['a1', '2z', 'aw', 'a']

In [45]:
reduce(find_max, m_list3)


Out[45]:
'aw'

filter()


In [46]:
def even_check(num):
    if num % 2 == 0:
        return True
    else:
        return False

In [47]:
even_check(56)


Out[47]:
True

In [48]:
even_check(5)


Out[48]:
False

In [49]:
m_list4 = [0,1,2,3,4,5]

In [50]:
filter(even_check, m_list4)


Out[50]:
[0, 2, 4]

In [51]:
filter(lambda num: num%2 == 0, m_list4)


Out[51]:
[0, 2, 4]

zip()


In [52]:
x = [1,2,3]

In [53]:
y = [4,5,6]

In [54]:
zip(x,y)


Out[54]:
[(1, 4), (2, 5), (3, 6)]

In [55]:
zip(x,x)


Out[55]:
[(1, 1), (2, 2), (3, 3)]

In [56]:
zip(x,x,y)


Out[56]:
[(1, 1, 4), (2, 2, 5), (3, 3, 6)]

In [57]:
z = ['a', 'b']

In [58]:
zip(x,y,z)


Out[58]:
[(1, 4, 'a'), (2, 5, 'b')]

In [59]:
zip(z,x,y)


Out[59]:
[('a', 1, 4), ('b', 2, 5)]

enumerate()


In [60]:
for (count, item) in enumerate(m_list3):
    print count, item


0 a1
1 2z
2 aw
3 a

In [61]:
for (count, item) in enumerate(m_list2):
    if count >= 2:
        break
    else:
        print count, item


0 a
1 z

all(), any()


In [62]:
m_list5 = [False, True, False, False, True]

In [63]:
any(m_list5)


Out[63]:
True

In [64]:
all(m_list5)


Out[64]:
False

complex()


In [65]:
complex(2,3)


Out[65]:
(2+3j)

In [66]:
complex(10,0.5)


Out[66]:
(10+0.5j)

In [67]:
complex('5+2j')


Out[67]:
(5+2j)

In [68]:
complex('58-52j')


Out[68]:
(58-52j)

In [69]:
complex('-5j')


Out[69]:
-5j

In [ ]:

Collections Module

defaultdict


In [70]:
from collections import defaultdict

In [71]:
# without using defaultdict
m_dict = {'k1': 1}

In [72]:
m_dict['k1']


Out[72]:
1

In [73]:
m_dict['k2']


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-73-5227cfb1df3f> in <module>()
----> 1 m_dict['k2']

KeyError: 'k2'

In [74]:
#using defaultdict

m_dict2 = defaultdict(object)

In [75]:
m_dict2['k1213']


Out[75]:
<object at 0x7f75dbfd2ca0>

In [76]:
for key in m_dict2:
    print key


k1213

In [77]:
m_dict3 = defaultdict(lambda : 0)

In [78]:
m_dict3['k1']


Out[78]:
0

In [79]:
m_dict3['k2'] = 2

In [80]:
m_dict3


Out[80]:
defaultdict(<function __main__.<lambda>>, {'k1': 0, 'k2': 2})

orderedDict


In [ ]:


In [81]:
# un-ordered dictionary
m_dict4 = {}
m_dict4['k1'] = 1
m_dict4['k2'] = 2
m_dict4['k3'] = 3
m_dict4['k4'] = 4
m_dict4['k5'] = 5

In [82]:
m_dict4


Out[82]:
{'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4, 'k5': 5}

In [83]:
for k,v in m_dict4:
    print k, v


k 3
k 2
k 1
k 5
k 4

In [84]:
for k,v in m_dict4.items():
    print k, v


k3 3
k2 2
k1 1
k5 5
k4 4

In [85]:
m_dict5 = {}
m_dict5['k4'] = 4
m_dict5['k2'] = 2
m_dict5['k5'] = 5
m_dict5['k1'] = 1
m_dict5['k3'] = 3

In [86]:
m_dict4 == m_dict5


Out[86]:
True

In [87]:
# ordered dict

from collections import OrderedDict

m_dict6 = OrderedDict()
m_dict6['k4'] = 4
m_dict6['k2'] = 2
m_dict6['k5'] = 5
m_dict6['k1'] = 1
m_dict6['k3'] = 3

m_dict7 = OrderedDict()
m_dict7['k1'] = 1
m_dict7['k2'] = 2
m_dict7['k3'] = 3
m_dict7['k4'] = 4
m_dict7['k5'] = 5

In [88]:
m_dict6 == m_dict7     # comparing two ORDERED dict


Out[88]:
False

In [89]:
m_dict5 == m_dict6     # comparing ORDERED & UN-ORDERED dict


Out[89]:
True

In [90]:
m_dict5 == m_dict7     # comparing ORDERED & UN-ORDERED dict


Out[90]:
True

In [91]:
m_dict4 == m_dict5     # comparing two UN-ORDERED dict


Out[91]:
True

In [92]:
m_dict7.values()


Out[92]:
[1, 2, 3, 4, 5]

namedtuple()


In [93]:
# namedtuple() assigns names to every element of tuple

In [94]:
m_tuple = (1,2,3,4,5,6,7,8,9)

In [95]:
m_tuple[0]


Out[95]:
1

In [96]:
m_tuple[5]


Out[96]:
6

In [97]:
from collections import namedtuple

In [98]:
Dog = namedtuple('DOG', 'age breed name')

In [99]:
m_dog = Dog(2, 'Lab', 'Tommy')

In [100]:
m_dog


Out[100]:
DOG(age=2, breed='Lab', name='Tommy')

In [101]:
m_dog.age


Out[101]:
2

In [102]:
m_dog.breed


Out[102]:
'Lab'

In [103]:
m_dog.name


Out[103]:
'Tommy'

In [104]:
m_dog[0]


Out[104]:
2

In [105]:
m_dog[1]


Out[105]:
'Lab'

In [106]:
m_dog[2]


Out[106]:
'Tommy'

Datetime


In [107]:
import datetime

In [108]:
m_time = datetime.time(5,25,1)

In [109]:
print m_time


05:25:01

In [110]:
print datetime.time.max


23:59:59.999999

In [111]:
print datetime.time.min


00:00:00

In [112]:
print datetime.time.resolution


0:00:00.000001

In [113]:
m_today = datetime.date.today()

In [114]:
print m_today


2018-01-15

In [115]:
m_today.timetuple()


Out[115]:
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=15, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=15, tm_isdst=-1)

In [116]:
m_today.day


Out[116]:
15

Python Debugger


In [3]:
import pdb

In [5]:
x = [1,23,45]
y = 85
z = 20

result = y*z
print result

pdb.set_trace()

result2 = y+z
print result2


1700
--Return--
> <ipython-input-5-c3ac6d4c011a>(8)<module>()->None
-> pdb.set_trace()
(Pdb) q
---------------------------------------------------------------------------
BdbQuit                                   Traceback (most recent call last)
<ipython-input-5-c3ac6d4c011a> in <module>()
      6 print result
      7 
----> 8 pdb.set_trace()
      9 
     10 result2 = y+z

/usr/lib/python2.7/bdb.pyc in trace_dispatch(self, frame, event, arg)
     51             return self.dispatch_call(frame, arg)
     52         if event == 'return':
---> 53             return self.dispatch_return(frame, arg)
     54         if event == 'exception':
     55             return self.dispatch_exception(frame, arg)

/usr/lib/python2.7/bdb.pyc in dispatch_return(self, frame, arg)
     89             finally:
     90                 self.frame_returning = None
---> 91             if self.quitting: raise BdbQuit
     92         return self.trace_dispatch
     93 

BdbQuit: 

In [6]:
## Advanced numbers

In [7]:
hex(12)


Out[7]:
'0xc'

In [9]:
hex(512)


Out[9]:
'0x200'

In [10]:
bin(1234)


Out[10]:
'0b10011010010'

In [11]:
bin(128)


Out[11]:
'0b10000000'

In [12]:
bin(512)


Out[12]:
'0b1000000000'

In [13]:
2**4


Out[13]:
16

In [14]:
pow(2,4)


Out[14]:
16

In [15]:
pow(2,4,3)


Out[15]:
1

In [16]:
abs(-56)


Out[16]:
56

In [17]:
round(2.154)


Out[17]:
2.0

In [18]:
round(3.845)


Out[18]:
4.0

In [19]:
round(3.8451258, 3)


Out[19]:
3.845

In [20]:
round(3.21548, 2)


Out[20]:
3.22

In [21]:
## Advanced Strings

In [22]:
m_str = 'hello world'

In [23]:
m_str.capitalize()


Out[23]:
'Hello world'

In [24]:
m_str.upper()


Out[24]:
'HELLO WORLD'

In [25]:
m_str


Out[25]:
'hello world'

In [26]:
m_str.lower()


Out[26]:
'hello world'

In [27]:
m_str.count('e')


Out[27]:
1

In [28]:
m_str.count('l')


Out[28]:
3

In [29]:
m_str.find('l')


Out[29]:
2

In [31]:
m_str.center(20, 'z')


Out[31]:
'zzzzhello worldzzzzz'

In [32]:
print 'hello\thi'


hello	hi

In [33]:
'hello\thi'.expandtabs()


Out[33]:
'hello   hi'

In [34]:
m_str2 = 'hello potter217'

In [35]:
m_str2.isalnum()


Out[35]:
False

In [36]:
m_str2.isalpha()


Out[36]:
False

In [37]:
m_str.isalnum()


Out[37]:
False

In [38]:
m_str.istitle()


Out[38]:
False

In [41]:
m_listComprehension = [x**3 for x in range(10)]

In [42]:
{str(x):x**3 for x in range(10)}


Out[42]:
{'0': 0,
 '1': 1,
 '2': 8,
 '3': 27,
 '4': 64,
 '5': 125,
 '6': 216,
 '7': 343,
 '8': 512,
 '9': 729}

In [43]:
m_listComprehension


Out[43]:
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

In [44]:
m_listComprehension.append([12, 85, 'djdbhsdbhb'])

In [45]:
m_listComprehension


Out[45]:
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, [12, 85, 'djdbhsdbhb']]

In [46]:
m_listComprehension.extend(['dsbhffbhs', 52.015, 45])

In [47]:
m_listComprehension


Out[47]:
[0,
 1,
 8,
 27,
 64,
 125,
 216,
 343,
 512,
 729,
 [12, 85, 'djdbhsdbhb'],
 'dsbhffbhs',
 52.015,
 45]

In [48]:
m_listComprehension.index(216)


Out[48]:
6

In [49]:
m_listComprehension.index(217)


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-49-dcaa144774e8> in <module>()
----> 1 m_listComprehension.index(217)

ValueError: 217 is not in list

In [50]:
m_listComprehension.insert(2, 'rustomPotter')

In [51]:
m_listComprehension


Out[51]:
[0,
 1,
 'rustomPotter',
 8,
 27,
 64,
 125,
 216,
 343,
 512,
 729,
 [12, 85, 'djdbhsdbhb'],
 'dsbhffbhs',
 52.015,
 45]

In [52]:
m_listComprehension.pop()


Out[52]:
45

In [53]:
m_listComprehension


Out[53]:
[0,
 1,
 'rustomPotter',
 8,
 27,
 64,
 125,
 216,
 343,
 512,
 729,
 [12, 85, 'djdbhsdbhb'],
 'dsbhffbhs',
 52.015]

In [54]:
m_listComprehension.pop(2)


Out[54]:
'rustomPotter'

In [57]:
m_listComprehension.remove(1)

In [58]:
m_listComprehension.reverse()

In [59]:
m_listComprehension


Out[59]:
[52.015,
 'dsbhffbhs',
 [12, 85, 'djdbhsdbhb'],
 729,
 512,
 343,
 216,
 125,
 64,
 27,
 8,
 0]

In [60]:
m_listComprehension.sort()

In [61]:
m_listComprehension


Out[61]:
[0,
 8,
 27,
 52.015,
 64,
 125,
 216,
 343,
 512,
 729,
 [12, 85, 'djdbhsdbhb'],
 'dsbhffbhs']

In [1]:
m_str = "Hariom Vinay"

In [5]:
print(m_str.rjust(5))


Hariom Vinay

In [6]:
print(m_str.rjust(100))


                                                                                        Hariom Vinay

In [7]:
m_str.replace('i', '(II)')


Out[7]:
'Har(II)om V(II)nay'

In [8]:
print(' hdhbsh hshdv  '.strip())


hdhbsh hshdv

In [1]:
d = {'cat': 'cute', 'dog': 'furry'}

In [3]:
print(d.get('cat', 'N/A'))


cute

In [4]:
help(set)


Help on class set in module __builtin__:

class set(object)
 |  set() -> new empty set object
 |  set(iterable) -> new set object
 |  
 |  Build an unordered collection of unique elements.
 |  
 |  Methods defined here:
 |  
 |  __and__(...)
 |      x.__and__(y) <==> x&y
 |  
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x.
 |  
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |  
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |  
 |  __iand__(...)
 |      x.__iand__(y) <==> x&=y
 |  
 |  __init__(...)
 |      x.__init__(...) initializes x; see help(type(x)) for signature
 |  
 |  __ior__(...)
 |      x.__ior__(y) <==> x|=y
 |  
 |  __isub__(...)
 |      x.__isub__(y) <==> x-=y
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |  
 |  __ixor__(...)
 |      x.__ixor__(y) <==> x^=y
 |  
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |  
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |  
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |  
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |  
 |  __or__(...)
 |      x.__or__(y) <==> x|y
 |  
 |  __rand__(...)
 |      x.__rand__(y) <==> y&x
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  
 |  __ror__(...)
 |      x.__ror__(y) <==> y|x
 |  
 |  __rsub__(...)
 |      x.__rsub__(y) <==> y-x
 |  
 |  __rxor__(...)
 |      x.__rxor__(y) <==> y^x
 |  
 |  __sizeof__(...)
 |      S.__sizeof__() -> size of S in memory, in bytes
 |  
 |  __sub__(...)
 |      x.__sub__(y) <==> x-y
 |  
 |  __xor__(...)
 |      x.__xor__(y) <==> x^y
 |  
 |  add(...)
 |      Add an element to a set.
 |      
 |      This has no effect if the element is already present.
 |  
 |  clear(...)
 |      Remove all elements from this set.
 |  
 |  copy(...)
 |      Return a shallow copy of a set.
 |  
 |  difference(...)
 |      Return the difference of two or more sets as a new set.
 |      
 |      (i.e. all elements that are in this set but not the others.)
 |  
 |  difference_update(...)
 |      Remove all elements of another set from this set.
 |  
 |  discard(...)
 |      Remove an element from a set if it is a member.
 |      
 |      If the element is not a member, do nothing.
 |  
 |  intersection(...)
 |      Return the intersection of two or more sets as a new set.
 |      
 |      (i.e. elements that are common to all of the sets.)
 |  
 |  intersection_update(...)
 |      Update a set with the intersection of itself and another.
 |  
 |  isdisjoint(...)
 |      Return True if two sets have a null intersection.
 |  
 |  issubset(...)
 |      Report whether another set contains this set.
 |  
 |  issuperset(...)
 |      Report whether this set contains another set.
 |  
 |  pop(...)
 |      Remove and return an arbitrary set element.
 |      Raises KeyError if the set is empty.
 |  
 |  remove(...)
 |      Remove an element from a set; it must be a member.
 |      
 |      If the element is not a member, raise a KeyError.
 |  
 |  symmetric_difference(...)
 |      Return the symmetric difference of two sets as a new set.
 |      
 |      (i.e. all elements that are in exactly one of the sets.)
 |  
 |  symmetric_difference_update(...)
 |      Update a set with the symmetric difference of itself and another.
 |  
 |  union(...)
 |      Return the union of sets as a new set.
 |      
 |      (i.e. all elements that are in either set.)
 |  
 |  update(...)
 |      Update a set with the union of itself and others.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T


In [16]:
animals = {'cat', '1456', 'dog', 'fish', '412', 217}
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))


#1: fish
#2: dog
#3: cat
#4: 1456
#5: 412
#6: 217

In [17]:
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))


#1: fish
#2: dog
#3: cat
#4: 1456
#5: 412
#6: 217

In [18]:
animals.add(45215565)

In [19]:
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))


#1: 45215565
#2: fish
#3: dog
#4: cat
#5: 1456
#6: 412
#7: 217

In [ ]: