Lists
Lists are arrays that grow as needed.
A list is written with this syntax: [val0, val1, ..., valn],
e.g., [2, 5, "a", []], is a list of two ints, a string, and an
empty list. (You can mix types within a Python list).
Here are basic operations on lists:
x = [1,2,3] # sets x to the list, [1,2,3]
print x[1] # You index a list like an array; prints 2
print x # prints the whole 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+3] # sets z to [5,7]
x = x + z # sets x to [1,2,3,4,5,7]
print x # prints the list, [1,2,3,4,5,7]
print len(x) # prints 6, the length of the list named by x
#You can write loops that process lists. Here is the usual way, a for-loop:
for item in x :
print item, item * item
# the loop prints 1 1
# 2 4
# ...
# 7 49
# The following while-loop does the same work as the above for-loop:
i = 0
while i != len(x) :
item = x[i]
print item, item * item
i = i + 1
if 3 in x : # asks if int 3 is present within list x
print "yes"
# You can mix ints, string, lists, etc., in the same list:
mix = [2, "abc", [2,4,'six'], 8] # also, a string can be written "abc" or 'abc'
for v in mix :
if isinstance(v, int) :
print "int is", v
elif isinstance(v, str):
print "string is", v
elif isinstance(v, list):
print "is a list:"
for i in v :
print i
else :
print "oh well!", v
Dictionaries
A dictionary (implemented in Python as a hash table) is similar to a record struct, but dictionaries
can grow as needed and the key set is not fixed in advance.
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"]