9 list[i:j] # returns list subset
10 list[-1] # returns last element
11 list[:-1] # returns all but the last element
14 list[i:j] = otherlist # replace ith to jth-1 elements with otherlist
18 list.extend(another_list)
19 list.insert(index, item)
20 list.pop() # returns and removes last element from the list
21 list.pop(i) # returns and removes i-th element from the list
22 list.remove(i) # removes the first item from the list whose value is i
23 list1 + list2 # combine two list
24 set(list) # remove duplicate elements from a list
26 list.reverse() # reverses the elements of the list in-place
30 zip(list1, list2) # returns list of tuples with n-th element of both list1 and list2
31 list.sort() # sorts in-place, returns None
32 sorted(list) # returns sorted copy of list
33 ",".join(list) # returns a string with list elements seperated by comma
39 "key" in dict # let's say this returns False, then...
40 dict["key"] # ...this raises KeyError
41 dict.get("key") # ...this returns None
42 dict.setdefault("key", 1)
46 for item in ["a", "b", "c"]:
47 for i in range(4): # 0 to 3
48 for i in range(4, 8): # 4 to 7
49 for i in range(1, 9, 2): # 1, 3, 5, 7
50 for key, val in dict.items():
51 for index, item in enumerate(list):
53 ### [String](https://docs.python.org/2/library/stdtypes.html#string-methods)
58 string.replace("-", " ")
61 "hi {name}" # same as "hi {}".format('name')
63 str.index(",") # same, but raises IndexError
77 /* escape characters */
78 >>> 'doesn\'t' # use \' to escape the single quote...
80 >>> "doesn't" # ...or use double quotes instead
82 >>> '"Yes," they said.'
84 >>> "\"Yes,\" they said."
86 >>> '"Isn\'t," they said.'
87 '"Isn\'t," they said.'
99 [fn(i) for i in list] # .map
100 map(fn, list) # .map, returns iterator
102 filter(fn, list) # .filter, returns iterator
103 [fn(i) for i in list if i > 0] # .filter.map
109 re.match(r'^[aeiou]', str)
110 re.sub(r'^[aeiou]', '?', str)
111 re.sub(r'(xyz)', r'\1', str)
113 expr = re.compile(r'^...$')
122 file = open("hello.txt", "r") # open in read mode 'r'
125 print(file.read()) # read the file
126 print fh.readline() # Reading line by line
129 ### Writing (overwrite)
132 file = open("hello.txt", "w") # open in write mode 'w'
135 text_lines = ["First line", "Second line", "Last line"]
136 file.writelines(text_lines)
144 file = open("Hello.txt", "a") # open in append mode
145 write("Hello World again")
152 with open("welcome.txt", "r") as file:
153 # 'file' refers directly to the "welcome.txt"
157 It closes the file automatically, no need for `file.close()`.