UPY Section 4: Python Overview | 20200916

In [1]:
def square(num):
    """
    this returns a square
    """
    return num*num

Use SHIFT and TAB on the cell below to see the comment

This can actually be used for ALL libraries!!

In [10]:
square(3)
Out[10]:
9

METHODS are functions you can call on objects. They affect the object or return

In Jupyter Notebook, we can click . and then TAB to get a list of methods for that object

PART 4: Lambda + map + filter

---- 'MAP' = I want to map THIS FUNCTION to THESE THINGS

In [4]:
# IMPETUS: I want to multiply this list-o-nums times 2
# PROBLEM: That's so manual!
# SOLUTION: Write a function & then MAP the list-o-nums to that function!

def times2(num):
    return num * 2

numbers = [1,2,3,4,5]
numbersTimes2 = list(map(times2,numbers))
In [5]:
numbersTimes2 # checking our work
Out[5]:
[2, 4, 6, 8, 10]
In [7]:
# PROBLEM: That still looks like A LOT of code to do something so little!
# SOLUTION: Put it on one line!

def times2(num): return num * 2
numbers = [1,2,3,4,5]
numbersTimes2 = list(map(times2,numbers))
numbersTimes2 # checking our work 
Out[7]:
[2, 4, 6, 8, 10]
In [8]:
# PROBLEM: That is STILL a lot! 
# SOLUTION: USE A LAMBDA!! (it basically just removes the unecessary extra words!)

## BEFORE
def times2(num): return num * 2
 
## AFTER
lambda num: num * 2
Out[8]:
<function __main__.<lambda>(num)>

---- 'FILTER' = I want to filter out some things!

In [9]:
# Get all odd numbers

list(filter(lambda x: x%2, numbers))
Out[9]:
[1, 3, 5]
In [13]:
name = "kendra"
# name. <-- check the methonds on a string!

d = {'k1': 1, 'k2':2}
# d. <-- check the methods on a dictionary!

lst = [2,3,4,5]
# lst. <-- check the methods on a list!
Out[13]:
{'k1': 1, 'k2': 2}

Touple Unpacking

In [14]:
my_tup = [(1,2),(3,4),(5,6)]

for a,b in my_tup:
    print(a)
1
3
5
In [ ]: