function

In [1]:
def times2(var):
    return var*2
In [4]:
seq = [1, 2, 3, 4, 5]
In [6]:
for num in seq:
    print(times2(num))
2
4
6
8
10
In [14]:
[times2(num) for num in seq] # alternative way (1 line code only !)
Out[14]:
[2, 4, 6, 8, 10]

map

In [19]:
list(map(times2, seq))   # maps the sequence to the function times2 and return it in the form of a list
Out[19]:
[2, 4, 6, 8, 10]

lambda

In [20]:
# def times2(var):return var*2  <-- alternative way to write the function
In [21]:
# lambda var:var*2   <-- lambda expression
In [22]:
t = lambda var:var*2
In [23]:
t
Out[23]:
<function __main__.<lambda>>
In [24]:
list(map(lambda num: num*3, seq))  # <-- utilize map and lambda 
Out[24]:
[3, 6, 9, 12, 15]

filter

In [25]:
filter(lambda num: num%2 == 0, seq)
Out[25]:
<filter at 0x104476208>
In [26]:
list(filter(lambda num: num%2 == 0, seq))
Out[26]:
[2, 4]

some useful methods

In [27]:
s = 'hello my name is Ade'
In [28]:
s.lower()
Out[28]:
'hello my name is ade'
In [29]:
s.upper()
Out[29]:
'HELLO MY NAME IS ADE'
In [30]:
s.split()
Out[30]:
['hello', 'my', 'name', 'is', 'Ade']
In [31]:
tweet = 'Go Ade! #Sports'
In [34]:
tweet.split('#')
Out[34]:
['Go Ade! ', 'Sports']
In [35]:
tweet.split('#')[1]  # get the name of the hashtag
Out[35]:
'Sports'
In [36]:
d = {'k1':'1', 'k2':'2'}
In [37]:
d.keys()
Out[37]:
dict_keys(['k1', 'k2'])
In [38]:
d.items()
Out[38]:
dict_items([('k1', '1'), ('k2', '2')])
In [39]:
d.values()
Out[39]:
dict_values(['1', '2'])
In [40]:
lst = [1,2,3]
In [41]:
lst.pop()  # get the last item and remove it from the list
Out[41]:
3
In [42]:
lst
Out[42]:
[1, 2]
In [43]:
first = lst.pop(0)   # get the 0th index element and remove it from the list
In [44]:
first
Out[44]:
1
In [46]:
lst
Out[46]:
[2]
In [47]:
lst.append(5)
In [48]:
lst
Out[48]:
[2, 5]

tuple unpacking

In [49]:
x = [(1,2), (3,4), (5,6)]
In [51]:
x[0][1]
Out[51]:
2
In [53]:
for item in x:
    print(item)
(1, 2)
(3, 4)
(5, 6)
In [57]:
[item for item in x]
Out[57]:
[(1, 2), (3, 4), (5, 6)]
In [55]:
for (a,b) in x:
    print(a)
1
3
5
In [56]:
for a,b in x:
    print(b)
2
4
6