14 list[i:j] # returns list subset
15 list[-1] # returns last element
16 list[:-1] # returns all but the last element
17 *list # expands all elements in place
20 list[i:j] = otherlist # replace ith to jth-1 elements with otherlist
24 list.extend(another_list)
25 list.insert(index, item)
26 list.pop() # returns and removes last element from the list
27 list.pop(i) # returns and removes i-th element from the list
28 list.remove(i) # removes the first item from the list whose value is i
29 list1 + list2 # combine two list
30 set(list) # remove duplicate elements from a list
32 list.reverse() # reverses the elements of the list in-place
36 zip(list1, list2) # returns list of tuples with n-th element of both list1 and list2
37 list.sort() # sorts in-place, returns None
38 sorted(list) # returns sorted copy of list
39 ",".join(list) # returns a string with list elements seperated by comma
46 "key" in dict # let's say this returns False, then...
47 dict["key"] # ...this raises KeyError
48 dict.get("key") # ...this returns None
49 dict.setdefault("key", 1)
50 **dict # expands all k/v pairs in place
54 for item in ["a", "b", "c"]:
55 for i in range(4): # 0 to 3
56 for i in range(4, 8): # 4 to 7
57 for i in range(1, 9, 2): # 1, 3, 5, 7
58 for key, val in dict.items():
59 for index, item in enumerate(list):
61 ### [String](https://docs.python.org/2/library/stdtypes.html#string-methods)
66 string.replace("-", " ")
69 f"hi {name}" # same as "hi {}".format('name')
71 str.index(",") # same, but raises IndexError
85 /* escape characters */
86 >>> 'doesn\'t' # use \' to escape the single quote...
88 >>> "doesn't" # ...or use double quotes instead
90 >>> '"Yes," they said.'
92 >>> "\"Yes,\" they said."
94 >>> '"Isn\'t," they said.'
95 '"Isn\'t," they said.'
107 [fn(i) for i in list] # .map
108 map(fn, list) # .map, returns iterator
110 filter(fn, list) # .filter, returns iterator
111 [fn(i) for i in list if i > 0] # .filter.map
117 re.match(r'^[aeiou]', str)
118 re.sub(r'^[aeiou]', '?', str)
119 re.sub(r'(xyz)', r'\1', str)
121 expr = re.compile(r'^...$')
130 file = open("hello.txt", "r") # open in read mode 'r'
135 print(file.read()) # read the entire file and set the cursor at the end of file
136 print file.readline() # Reading one line
137 file.seek(0, 0) # place the cursor at the beginning of the file
140 ### Writing (overwrite)
143 file = open("hello.txt", "w") # open in write mode 'w'
144 file.write("Hello World")
146 text_lines = ["First line", "Second line", "Last line"]
147 file.writelines(text_lines)
155 file = open("Hello.txt", "a") # open in append mode
156 file.write("Hello World again")
163 with open("welcome.txt", "r") as file:
164 # 'file' refers directly to "welcome.txt"
167 # It closes the file automatically at the end of scope, no need for `file.close()`.