| Primitive Datatypes & Operators |
|---|
| 1 < 2 < 3 ---> True |
| "This is a string"[0] ---> 'T' |
| "%s can be %s" % ("strings", "interpolated") |
| "{0} can be {1}".format("strings", "formatted") |
| "{name} wants to eat {food}".format(name="Bob", food="lasagna") |
| None is object, when compare objects, use "is": "etc" is None ---> False |
| None, 0, empty string/lists all evaluates to False |
Variables and Collections
| list = [1, 2, 4] | Note | Output |
|---|---|---|
| li.append(3); li.pop() ; li[-1] | pop last element; index -1 get last num | [1, 2, 4, 3]; [1, 2, 4]; 3 |
| li[1:3]; li[2:]; li[:3]; del lli[2] | [a:b]-->[a,b); [a:] omit end;[b:] first b Ns | [2, 4]; [4, 3]; [1, 2, 4]; [1, 2, 3] |
| list1 + list2 original lists l1 l2 intact | li.extend(li2), li is changed & longer | 1 in li --> True; len(li) |
| tuple = (1, 2, 3) immutable | all doable on list is also on tuples | |
|---|---|---|
| a, b, c = (1, 2, 3) --> a=1, b=2, c=3 | d, e, f = 4, 5, 6 --> tuples created automatically | e, d = d, e for swapping |
| dic = {"one": 1, "two:2, "three", 3} | output | |
|---|---|---|
| dic["one"]; dict.keys(); dic.values() | keys() & values() order not guaranteed | 1; ["three", "two", "one"]; [3, 2, 1] |
| "one in dict; 1 in dict; "not exist" in dict | can only check if key in | True; False; Error |
| dict.get("key"); doct.get("one") | safer get, avoid error if not exist | None; 1 |
| dict.get("a", 9); | return 9 if key "a" missing; | |
| dict.setdefault("a", 8); | dict.setdefault("a", 9) | set default pair with 8, cannot be override. Still 8. |
line 310