# using just the library name...
import math
print (math.sqrt(2))
# importing just one function...
from math import sqrt
print (sqrt(2))
# importing all functions and constants...
# Note: the imported function/constant names may interfere with your own function/constant names (be careful)...
from math import *
print (math.e)
# displaying the attributes (functions and constants) of a library...
import math
dir(math)
a value is considered False if
it's considered True otherwise
# the following will not print anything...
a=0
if a:
print (a)
(You'll need to try these examples outside of Jupyter notebooks)
sys.argv is an array of the command-line arguments typed on the line from which the program is excuted.
For instance, suppose you've got the following program in the file: fred.py ...
import sys.argv
for i in range(len(sys.argv)):
print (i,sys.argv[i])
...and then you execute the program from the command-line as follows...
$ python fred.py harry george
the program will print:
0 fred.py
1 harry
2 george
You can create lists quite easily in a single line of code.
# create a list of squares (e.g. [0,1,4,9,...])
sq = [x*x for x in range(10)]
# a list of squares divisible by 3
sq3 = [x*x for x in range(20) if x%3 == 0]
# a new list of strings from an old list of names, prepending each name with a phrase
get_serious = ['I love you '+sweetie for sweetie in names]
# Suppose you have a list of pairs of numbers (e.g. pairs = [[1,5],[4,7],...]) and you want the sum of each
the_sum = [x+y for [x,y] in pairs]
# converting a dictionary into a list of pairs (Python 2)
pairs = [[a,b] for a,b in d.iteritems()]
# converting a dictionary into a list of pairs (Python 3)
pairs = [[a,b] for a,b in iter(d.items())]
# you have a file called "fred.txt" containing one number on each line and wanted to print all of the positive numbers out on one line separated by commas
','.join([x for x in open('fred.txt','rU').read().split() if x and float(x)>0])
When working with large lists (or other collections), there are more and less efficient ways to build or access them.
When creating a large list by adding elements, use the append method rather than simple concatenation...
L += [12] # slow version because in L = L + [12], a copy of L is made, the element 12 is appended, and the old version is erased.
L.append(12) # fast version because the original list is simply extended
If you're going to be looking up elements in an list frequently, you might want to make a copy of the list into a set, which is hashable (if the list contains hashable elements, like strings or numbers, but not sublists). Looking elements up in hashed collections, like dictionaries or sets, is very much faster than looking them up in lists.
S = set(L)
'fred' in S # very fast, especially if you're going to do this many times
'fred' in L # slower