l = [1, 2, 3, 4, 5, "six"]
print(l)
print(type(l))
[1, 2, 3, 4, 5, 'six'] <class 'list'>
len(l)
6
print(4 in l, 7 in l)
True False
Indexing lists:
print(l)
[1, 2, 3, 4, 5, 'six']
l
[1, 2, 3, 4, 5, 'six']
l[0]
1
l[-1]
'six'
print(l)
[1, 2, 3, 4, 5, 'six']
l[2:4] ## slicing
[3, 4]
l[3:]
[4, 5, 'six']
Modifying lists:
l[-1] = 'seven'
l[2:4] = [7, 8]
l
[1, 2, 7, 8, 5, 'seven']
l.pop()
'seven'
l
[1, 2, 7, 8, 5]
l.append("eight")
l
[1, 2, 7, 8, 5, 'eight']
l.reverse()
l
['eight', 5, 8, 7, 2, 1]
Concatenation and repetition:
l = [7, 1, 2]
r = [9, 6, 8]
l + r*2
[7, 1, 2, 9, 6, 8, 9, 6, 8]
List comprehension:
l = [1, 2, 3, 4]
[[x**2, 1] for x in l]
[[1, 1], [4, 1], [9, 1], [16, 1]]
[x**2 for x in l if x % 2 == 0]
[4, 16]
d = {'a': 2, 'b': 2, 3: 2, 'b': 5}
d['a'] ### lookup
2
d.keys()
dict_keys(['a', 'b', 3])
d.values()
dict_values([2, 5, 2])
s = {1, 2, 3, 1, 3, 1, 4}
s
{1, 2, 3, 4}
s.intersection([3, 4, 5])
{3, 4}
s.union([7])
{1, 2, 3, 4, 7}
pairdict = {[1, 2]: 3}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-28-4ab7d016ea9e> in <module> ----> 1 pairdict = {[1, 2]: 3} TypeError: unhashable type: 'list'
pairset = {[1,2], [3,4]}
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-29-6b3ef5633f01> in <module> ----> 1 pairset = {[1,2], [3,4]} TypeError: unhashable type: 'list'
v1 = "abcd" * 10
v2 = "abcd" * 10
v3 = v2 + 'x'
print(v1, v2, v3)
hash(v1), hash(v2), hash(v3)
abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdx
(4809842418838812611, 4809842418838812611, -4505499860472041403)
t = (1, 2, 'three')
len(t)
3
t[1]
2
t[1] = 4 ## cannot be modified
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-34-12c5f1992471> in <module> ----> 1 t[1] = 4 ## cannot be modified TypeError: 'tuple' object does not support item assignment
pairdict = {(1,2): 3}
pairset = {(1,2), (3,4)}
def square_sum(x, y):
v = x*x + y*y
return v
print(square_sum(2, 2))
8
def square_sum2(x, y=1):
return x**2 + y**2
square_sum2(2)
5
square_sum2(x=1, y=3)
10
square_sum2(1, 3)
10
def square_sum3(x, y=1, z=2):
return x**2 + y**2 + z
square_sum3(2)
7
square_sum3(2, z=3)
8
def apply(function, argument):
return function(argument)
apply(lambda x: x + 1, 3)
# lambda arg1,arg2,... : expression, value1, value2,...
4
# m > n ? m : n
my_max = lambda m, n: m if m > n else n
print(my_max(10, 3))
10
l = [1, 2, 3]
#apply(square_sum2, 2)
[square_sum2(x) for x in l]
[2, 5, 10]
things = ["cat", "apple", "boat"]
sorted(things) # alphabetically, upper case first
['apple', 'boat', 'cat']
sorted(things, key=lambda x: len(x))
['cat', 'boat', 'apple']
enumerate(things)
<enumerate at 0x7f5884527b40>
list(enumerate(things, 2)) ## the second argument is the first index
[(2, 'cat'), (3, 'apple'), (4, 'boat')]
### sum over collections
numbers = [14, 13, 15]
sum(numbers) ### works with non-numbers, too
42
sum([['foo', 'bar'], ['baz'], ['abced', 'efgh']], [])
['foo', 'bar', 'baz', 'abced', 'efgh']
things
['cat', 'apple', 'boat']
list(zip(things, reversed(things), numbers))
[('cat', 'boat', 14), ('apple', 'apple', 13), ('boat', 'cat', 15)]
[str(x) + ' ' + y + 's' for x, y in zip(numbers, things)]
['14 cats', '13 apples', '15 boats']
## By the way: there are better ways to interpolate strings:
"{count:.2f} {thing}s".format(thing="zebra", count=3.14159)
'3.14 zebras'
## or even this:
x = 1
y = 2
f'{x} + {y} equals {x+y}'
'1 + 2 equals 3'
range(12)
range(0, 12)
list(range(12)) ## endpoint is not included
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
sum(range(12))
66
list(range(32, 7, -3))
[32, 29, 26, 23, 20, 17, 14, 11, 8]
some_guy = 'Fred'
names = []
names.append(some_guy)
names2 = names
names2.append('George')
some_guy = 'Bill'
print(some_guy, names, names2)
Bill ['Fred', 'George'] ['Fred', 'George']
import copy
some_guy = 'Fred'
names = []
names.append(some_guy)
names2 = copy.deepcopy(names)
names2.append('George')
some_guy = 'Bill'
print(some_guy, names, names2)
Bill ['Fred'] ['Fred', 'George']
Understand how Python works "under the hood": http://www.pythontutor.com/visualize.html
help()
functionimport math
math.log2(1024)
10.0
math.log(math.e)
1.0
math.cos(math.pi)
-1.0
import itertools
perms = itertools.permutations([1, 2, 3], r=2)
# r-length tuples, all possible orderings, no repeated elements
# default r: length of the iterable
for p in perms:
print(p)
(1, 2) (1, 3) (2, 1) (2, 3) (3, 1) (3, 2)
combs = itertools.combinations([1, 2, 3], r=2)
# r-length tuples, in sorted order, no repeated elements
print(list(combs))
[(1, 2), (1, 3), (2, 3)]
import random as rnd ## you can re-name imported modules
rnd.randint(1, 6) ## Here, the end points are both included
2
print(things)
rnd.choice(things)
['cat', 'apple', 'boat']
'boat'
rnd.sample(range(1000), 5)
[472, 14, 128, 624, 913]
## Modules can have sub-modules
import urllib.request as rq
response = rq.urlopen("http://en.wikipedia.org/wiki/Python")
print(response.read(151).decode('utf8'))
<!DOCTYPE html> <html class="client-nojs" lang="en" dir="ltr"> <head> <meta charset="UTF-8"/> <title>Python - Wikipedia</title> <script>document.docume
Linux:
sudo apt-get install python3-numpy
(or equivalent for your distro)pip install numpy
Windows and Mac:
import numpy as np
np.version.full_version
'1.17.2'
array
s¶a = np.array([1, 2, 3])
type(a)
numpy.ndarray
a.dtype
print(128 ** 128)
print(np.int64(128 ** 128))
528294531135665246352339784916516606518847326036121522127960709026673902556724859474417255887657187894674394993257128678882347559502685537250538978462939576908386683999005084168731517676426441053024232908211188404148028292751561738838396898767036476489538580897737998336
--------------------------------------------------------------------------- OverflowError Traceback (most recent call last) <ipython-input-73-d91fae5e563b> in <module> 1 a.dtype 2 print(128 ** 128) ----> 3 print(np.int64(128 ** 128)) OverflowError: Python int too large to convert to C long
a + 1
array([2, 3, 4])
a * 1.25
array([1.25, 2.5 , 3.75])
a ** 3
array([ 1, 8, 27])
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
a + b
array([5, 7, 9])
a * b
array([ 4, 10, 18])
a.dot(b)
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
32
$a \cdot b = a_1 b_1 + a_2 b_2 + a_3 b_3$
a
array([1, 2, 3])
len(a)
3
a.size
3
a.shape
(3,)
v = np.array([[1, 2, 3]])
v
array([[1, 2, 3]])
v.shape
(1, 3)
m = np.array([[1, 2, 3], [4, 5, 6]])
m
array([[1, 2, 3], [4, 5, 6]])
m.shape
(2, 3)
m2 = np.array([[3, 2], [4, 5], [6, 7]])
m2
array([[3, 2], [4, 5], [6, 7]])
print('v:', v.shape, 'm:', m.shape, ' m2:', m2.shape)
v: (1, 3) m: (2, 3) m2: (3, 2)
m = array([[1, 2, 3], ; m2 = array([[3, 2],
[4, 5, 6]]) [4, 5],
[6, 7]])
m.dot(m2)
array([[29, 33], [68, 75]])
m2.dot(m)
array([[11, 16, 21], [24, 33, 42], [34, 47, 60]])
np.arange(0, 10, 2) ## start, stop, stepsize
# np.array(range(0, 10, 2)) ## equivalent
array([0, 2, 4, 6, 8])
np.linspace(0, 1, 3) ## start, stop, count
array([0. , 0.5, 1. ])
a = np.linspace(0, np.pi, 4)
a
array([0. , 1.04719755, 2.0943951 , 3.14159265])
np.cos(a)
array([ 1. , 0.5, -0.5, -1. ])
np.zeros(9)
array([0., 0., 0., 0., 0., 0., 0., 0., 0.])
np.zeros([3, 4])
array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]])
np.ones([2, 2])
array([[1., 1.], [1., 1.]])
m
array([[1, 2, 3], [4, 5, 6]])
np.ones_like(m)
array([[1, 1, 1], [1, 1, 1]])
np.eye(5) ## identity matrix
array([[1., 0., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.]])
np.eye(5, 7, -1) ## rows, columns, diagonal offset.
array([[0., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [0., 1., 0., 0., 0., 0., 0.], [0., 0., 1., 0., 0., 0., 0.], [0., 0., 0., 1., 0., 0., 0.]])
x = np.random.rand(4, 3) ### I.i.d. uniform in [0, 1];
### randn() for gaussian
2*x + 1
array([[2.00957291, 2.99538573, 1.48395068], [2.00777067, 1.22702353, 1.05240387], [2.94676883, 1.78339226, 2.88969613], [1.89841747, 2.48200282, 2.14871356]])
m
array([[1, 2, 3], [4, 5, 6]])
m.T ## Transpose
array([[1, 4], [2, 5], [3, 6]])
m.flatten()
array([1, 2, 3, 4, 5, 6])
m
array([[1, 2, 3], [4, 5, 6]])
m.sum()
21
m.shape
(2, 3)
axis=1
-------->
[[1, 2, 3], | axis=0
[4, 5, 6]] \/
m.sum(axis=0)
array([5, 7, 9])
m.sum(axis=1)
array([ 6, 15])
m3 = np.array([[0, 1],
[2, 3]])
m3_inv = np.linalg.inv(m3) ## compute the inverse
m3.dot(m3_inv)
array([[1., 0.], [0., 1.]])
matplotlib
library¶%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([0, 1, 2], [1, 0, -0.5], 'o--b', linewidth=5);
# o: symbol for points
# --: use dashes as line
# g: color is green
xvals = np.linspace(0, 2*np.pi, 100)
yvals = np.sin(xvals)
plt.plot(xvals, yvals)
plt.xticks(np.linspace(0, 2*np.pi, 7))
plt.title("Sine curve, one period")
plt.xlabel("x"); plt.ylabel("y")
plt.grid();
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x, y);
y = np.random.rand(20)
x = np.arange(20)
plt.bar(x, y, facecolor='green');
y = np.random.randn(100000) * 2 + 5 ### mean 5, std.dev. 2
plt.hist(y, bins=500, facecolor='lightgray');