x = [1,2,3] # sets x to the list, [1,2,3] x.append(4) # resets x to [1,2,3,4] y = x[1] # sets y to 2 (you index a list like an array) z = [(y*y)+1, 4+2] # sets z to [5,6] x = x + z # sets x to [1,2,3,4,5,6] print x # prints the list, [1,2,3,4,5,6] print len(x) # prints 6, the length of the list named by x a = x # a is aliased to x (a's cell holds x's handle) a[0] = 9 print x # prints the list, [9,2,3,4,5,6] b = x[:] # sets b to a fresh copy of x's elements (see "slicing", below) if isinstance(x, list): # asks if x's value is a list for item in x : # the for-loop iterates through x's elements print item, item * item # the loop prints 9 81 # 2 4 # ... # 6 36 # this loop does the same work as the for-loop: i = 0 while i != len(x) : item = x[i] print item, item * item i = i + 1 if y in x : # asks if y's value is present within list x print "yes" # lists can be "sliced" (sublist-ed): x = [2, 4, 6, 8, 10] y = x[2:] # "slice out" sublist x[2], x[3], ..., to the end and assign to y z = x[:3] # "slice out" sublist up to, but not including, element 3 print x, y, z # prints [2,4,6,8,10] [6,8,10] [2,4,6] print x[1:4] # prints [4,6,8], namely, elements 1 up to, not including, 4 # how to emulate a stack with slicing, where the top is on the left: st = [] # empty st = [2] + st # push 2 st = [4] + st # push 4 print st[0] # print top st = st[1:] # pop # Using append and pop to emulate a stack, where the top is on the right: st = [] # empty st.append(2) st.append(4) # st has value [2,4] print st[len(st)-1] # prints top value, 4 print st[-1] # also prints 4, since negative ints index from the right (!) n = st.pop() # pop is a built-in method print n, st # prints 4 [2] # Python has *list comprehensions*, which save a lot of coding! vec = [2, 3, 4, 5, 6] vec2 = [x*x for x in vec] # sets vec2 to [4,9,16,25,36] vec3 = [ x*x for x in vec if x % 2 == 1 ] # sets vec3 to [9,25] # Here is cute trick that exposes that lists are really objects: if x in x : print "is this possible?!" # Actually, it is: x = ["boo"] # x.append(x) # Now, x in x computes to True (why?)
A dictionary is written with this syntax: {key0: val0, key1: val1, ... keyn: valn}, e.g., {"p": True, "q": False, 99: {}} is a dictionary that has entries for the keys "p", "q", and 99. (You can mix keys and values of different type, but lists and dictionaries cannot themselves be keys.)
Here are basic operations on dictionaries:
d = {"p": True, "q": False, 99: {}} # sets d to {"p":True, "q":False, 99:{}} x = d["q"] # sets x to False d["r"] = not x # adds new key:val pair to d, which now is # {"p":True, "q":False, 99:{}, "r":True} d["q"] = 100 # resets the value of the "q" key; d is # {"p":True, "q":100, 99:{}, "r":True} print d # prints the dict, but the keys might # be in nonsorted order, since the dict # is implemented as a hash table if isinstance(d, dict): # asks if d's value is a dictionary for key in d : # like the for-loop for lists, enumerates each print key, d[key] # key within d and uses it in the body if "s" in d : # asks if d holds a key named "s" print d["s"] del d["q"] # deletes the entry for "q" from the dictionary. Be careful. # how to print a dictionary's contents in sorted order: ids = d.keys() ids.sort() for i in ids: print i, ":", d[i]You can build a list of dictionaries or a dictionary of lists, or you can mix together dictionaries, lists, ints, strings, etc., in a single data structure.
g = 4 def p(x) : print x + g // it is always ok to reference a global var def q(y) : global g // we are declaring that we want update rights to global var g g = y // we updated global var g def r(y) : g = 99 // BEWARE: the g assigned here is not declared "global" so it is a new local var print y + g p(2) // prints 6 q(3) print g // prints 3 r(1) // prints 100When a data structure is global, a function can change a component of the global structure without the global declaration! See how:
table = {'a': 4, 'b': 6} def insert(key, value): table[key] = value // the handle to table is not updated, but one of its components is.... def erase(): global table; table = {} // table's handle (value) is updated, so the global declaration is required insert('b', 99) print table // prints {'a': 4, 'b': 99} erase() print table // prints {}If you write a script and you encounter an error where it seems that some variable "just isn't getting assigned when it is supposed to", then you are likely missing a global declaration!