Python 3

Functions


In [1]:
import math
def euclidean_distance(x1, y1, x2, y2):
    return math.sqrt((x1 - x2) ** 2 + (y1-y2) ** 2)

In [2]:
euclidean_distance(0,0,1,1)


Out[2]:
1.4142135623730951

We can unpack a list or tuple into positional arguments using a star *:


In [3]:
values_list = [0,0,1,1]
euclidean_distance(*values_list)


Out[3]:
1.4142135623730951

In [4]:
values_tuple = (0,0,1,1)
euclidean_distance(*values_tuple)


Out[4]:
1.4142135623730951

Similarly, we can use double star ** to unpack a dictionary into keyword arguments.


In [11]:
values_dict = { 'x1': 0, 'y1': 0, 'x2': 1, 'y2': 1 }
euclidean_distance(**values_dict)


Out[11]:
1.4142135623730951

In [13]:
list(zip([1,2,3,4,5,6]))


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

Comprehensions

With comprehensions, we can build a sequence based on another iterable.


In [6]:
# List comprehension
[num ** 2 for num in range(-10, 11)]


Out[6]:
[100, 81, 64, 49, 36, 25, 16, 9, 4, 1, 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In [7]:
[num ** 2 for num in range(-10, 11) if num > 0]


Out[7]:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In [8]:
# Set comprehension
names = [ 'Bob', 'JOHN', 'alice', 'bob', 'ALICE', 'J', 'Bob' ]
{ name[0].upper() + name[1:].lower() for name in names if len(name) > 1 }


Out[8]:
{'Alice', 'Bob', 'John'}

Dictionary comprehension


In [9]:
s = "Action Is Eloquence"
counts = dict()
for char in s:
    counts[char] = counts.get(char, 0) + 1
counts


Out[9]:
{' ': 2,
 'A': 1,
 'E': 1,
 'I': 1,
 'c': 2,
 'e': 2,
 'i': 1,
 'l': 1,
 'n': 2,
 'o': 2,
 'q': 1,
 's': 1,
 't': 1,
 'u': 1}

In [10]:
freq = { 
    k.lower() : counts.get(k.lower(), 0) + counts.get(k.upper(), 0)
    for k in counts.keys() if k.isalpha()
}
freq


Out[10]:
{'a': 1,
 'c': 2,
 'e': 3,
 'i': 2,
 'l': 1,
 'n': 2,
 'o': 2,
 'q': 1,
 's': 1,
 't': 1,
 'u': 1}