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