The python Tutorial is a good stuff to learn Python. I have already read it sketchily before, but didn't foucs on some detail things. This time I read it again and write some notes for reference next time.
Data Structures More on Lists list.append(x) : Equivalent to a[len(a):] = [x] list.extend(L) : Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L list.insert(i, x) : The first argument is the index of the element before which to insert. a.insert(len(a), x) == a.append(x) . list.remove(x) : Remove the first item form the list whose value is x. list.pop([i]) : Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list.(parameters with square brackets are optional) list.clear() : Remove all item from the list. Equivalent to del a[:] list.index(x) : Return the index in the list of the first item whose value is x. list.count(x) : Return the number of times x appears in the list. list.sort(key=None, reverse=False) : Sort the items of the list in place. list.reverse() : Reverse the elements of the list in place. list.copy() : Return a shallow copy of the list. Equivalent to a[:] . Using Lists as StacksUse append and pop .
Using Lists as QueuesLists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from beginning of a list is slow.
Better to use collections.deque .
List Comprehensions x = [item for item in series] x = [do_something(item) for item in series if expression] Nested List ComprehensionsThe initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.
Example: [[row[i] for row in matrix] for i in range(4)] . The del statementRemove an item from a list given its index. (Do not return a value) It can also remove slices from a list.
del can also be used to delete entire variables: del a .
Tuples and SequencesTuples are immutable , and usually contain a heterogeneous sequence of elements that are accessed via unpacking or indexing. List are mutable , and their element are usually homogeneous and are accessed by iterating over the list.
Empty tuples are constructed by and empty pair of parentheses: empty = () A tuple with one item is constructed by following a value with a comma: sigleton = 'hello',The statement t = 1, 2, 'hello' is an example of tuple packing : the values are packed together in a tuple. The reverse operation is also possible: x, y, z = t .
Sets{} or set() function can be used to create sets. Note: to create an empty set you have to use set() , not {} ; the latter creates an empty dictionary.
Example:
a = set('abracadabra') b = set('alacazam') a - b : letters in a but not in b a | b : letters in either a or b a & b : letters in both a and b a ^ b : letters in a or b but not bothSimilaryly to list comprehensions, set comprehensions are also supported.
DictionariesDictionaries are indexed by keys, which can be any immutable type; strings and numbers can slways be keys. Tuples can be used as keys if they contain only one kind of item. You can't use use lists as keys, since lists can be modified in place using index assignments, slice assignments, or method like append() and extend().
It is best to think of a dictionary as an unordered set of key: value pairs.
del can delete a key: value list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, use sortted(d.keys()) instead). To check whether a single key is in the dictionary, use the in keyword. ( in or not in ) Dict comprehensions can be used to create dictionaries from arbitrary key and value expressions: {x: x**2 for x in range(10)} When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments: dic(sape=1, guido=2, jack=3) => {'sape': 1, 'jack': 3, 'guido': 2} Looping TechniquesWhen looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
knights = {'gallahad': 'the pure', 'robin': 'the brave'} for k, v in knights.items(): print(k, v)When looping through a sequence, the position index and correspoding value can be retrieved at the same time using the enumerate() function.
for i, v in enumerate(['tic', 'tac', 'toe']): print(i, v)To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
numbers = [1, 2, 3] names = ['one', 'two', 'three'] for number, name in zip(numbers, names): print('Number: {0}, Name: {1}'.format(number, name))To loop over a sequence in sorted order, use the sorted() function which return a new sorted list while leaving the source unaltered. for item in soted(list)
It is sometimes tempting to change a list while you are looping over it; however, it is often simple and safer to create a new list instead.
More on Conditions in and not in : check whether a value occurs (or not) in a sequence. is and is not : compare whether two objects are really the same object; this only matters for mutable objcts like lists. Comparisons can be chained. a < b == c and and or are short-circuit operators Comparing Sequences and Other TypesThe comparison uses lexicographical ordering.
ModulesA module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module's name (as a string) is available as the value of the global variable __name__ .
More on ModulesNote that in general the practice of importing * from a module is frowned upon, since it often causes poorly readable code. (It ok to use in interactive sessions.)
It's one module you want to test interactively, use importlib.reload() .
import importlib importlib.reload(modulename) Executing modules as scripts if __name__ == "__main__": codeThis is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).
The Module Search PathWhen a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path , it is initialized from these locations:
The directory containing the input script (or the current directory when no file is specified). PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH ). The installation-dependent default.After initialization, Python programs can modify sys.path . The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory.
"Compiled" Python filesPython caches the compiled version of each module in the __pycache__ directory. It generally contains the Python version number. This naming convention allows compiled modules from dirrerent release and different version of Python to coexist. (Example: __pycache__/fib.python-27.pyc )
Python check the modification date of the source against the compiled version to see if it's out of date and needs to be recompiled.
Standard Modules >>> import sys >>> sys.ps1 '>>> ' >>> sys.ps2 '... ' >>> sys.ps1 = 'C> ' C> print('Yuck!') Yuck!The variable sys.path is a list of strings that determines the interpreter's search path for modules. You can modify it using standard list operations.
The dir() FunctionThe built-in function dir() is used to find out which names a module defines.
Without arguments, dir() lists the names you have defined currently.
It list all types of names: variable, modules, functions, etc.
Input and Output Methods of File ObjectsIt is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exceptiohn is raissed on the way. It is also much shorter thatn writing equivalent try-finally blocks:
with open('workfile', 'r') as f: read_data = f.read()