What's in a name? That which we call a rose by any other name would smell as sweet.
len()
#!/usr/bin/env python3 l = [3, 5, 1, 9] ordered = list(range(8)) ordered = list(range(3, 8)) ordered = list(range(12, 2, -2)) print(len(l)) print(ordered.sort()) print(ordered)
iterations = 1000000 l = [7, 9, 3] # initial content for i in range(iterations): l.insert(0, 0) # slow l = [7, 9, 3] # initial content l.reverse() for i in range(iterations): l.append(0) # fast l.reverse()
first = [1, 2, 3] second = first second[1] = 50
list()
or slicing [:]
first = [1, 2, 3] second = first[:] second[1] = 50
a_tuple = (3, 54, 2) t2 = (3, )
#!/usr/bin/env python3 from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(11, y=22) # instantiate with positional args or keywords print(p[0] + p[1]) # indexable like a plain tuple print(p.x + p.y) # fields also accessable by name
result = "Joe, 117" name, score = result.split(",") score = int(score)
def read_result(result): name, score = result.split(",") return name, int(score) # ... result = "Joe, 117" name, score = read_result(result)
a, b = b, a
dict
d = {"key1": "value1", "key2": "value2"}
dict.keys()
dict.values()
dict.items()
dict
d = {} d["key1"] = "value1" d["key2"] = "value2" d["key1"] = "new value"
#!/usr/bin/env python3 d = {"telephone": "+43(0)316/380-1234", "email": "contact@uni-graz.at", "office": "Resowi, E3"} for key in d: print(key, "--", d[key]) # alternatives for key in d.keys(): print(key) for value in d.values(): print(value) for key, value in d.items(): print(key, "--", value)
d = {"telephone": "+43(0)316/380-1234", "email": "contact@uni-graz.at", "office": "Resowi, E3"} for key in sorted(d.keys()): print(key, "--", d[key])
set
s = {1, 4, 5, 3, 1, 3, 5, 4, 3, 1, 3, 4}
s1 = {1, 4, 5, 3, 1, 3, 5, 4, 3, 1, 3, 4} s2 = {7, 8, 3, 9, 2, 6} intersection = s1.intersection(s2) # `&` operator union = s1.union(s2) # `|` operator difference = s1.difference(s2) # `-` operator
#!/usr/bin/env python3 matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for row in matrix: for index, elem in enumerate(row): row[index] = elem ** 2
np_matrix.py
#!/usr/bin/env python3 import numpy as np print("np.zeros([3,4])\n", np.zeros([3,4]), sep='') a1 = np.ones([4,3]) print("np.ones([4,3])\n", a1, sep='') print("3 * np.ones([4,3])\n", 3 * a1, sep='') a = np.arange(15).reshape(3, 5) m = np.matrix(np.arange(6).reshape(2, 3)) print("matrix m\n", m, sep='') print("array a\n", a, sep='') print("m * a\n", m * a, sep='') print("m.T (transposed)\n", m.T, sep='') print("m.I (inverse)\n", m.I, sep='')