Skip to content
Kenny Yu edited this page Nov 4, 2013 · 4 revisions

Prereqs

Tuples

Tuples allow us to pack multiple values together into one variable. See the python documentation for tuples for more information.

Open tuples.py for examples.

defgen_tuple(s):
""" Returns a tuple of (input, length of input) """return (s, len(s))
v=gen_tuple("foood")
printv
(s, n) =vprintsprintn

You should see the following output: (python tuples.py)

('foood', 5)
foood
5

Strings

Make sure you are in the examples directory.

Strings are groups of characters strung together. You can think of a string as a sequence of chars. Open up strings.py:

s="foood cake cheese"# print out the length of the string# len() is a builtin.printlen(s)
# split string by spaces, return list of wordswords=s.split()
printwordsprintlen(words)
# keyfunc and keyfunc2 are exactly the same# lambdas are just syntactic sugar to allow you# to declare one-liner functions.keyfunc=lambdaword : len(word)
defkeyfunc2(word):
returnlen(word)
# sort words by length of the word# The "key" argument of sorted tells us how to sort the list.## Example:# For the list: ["a", "aaa", "aa"],# keyfunc will be appled on all the elements: [1, 3, 2]# and then sorted: [1, 2, 3]# and then replaced with their original entries: ["a", "aa", "aaa"]words_sorted=sorted(words, key=keyfunc)
printwords_sorted# What else can you call on s?# (i.e. for what `foo` can we do `s.foo()`?)# To see what methods you can call on a variable, open up the top# level, then enter:## s = "food"# dir(s)## This will dump a list of all the things you can call the variable with.# E.g. "join" will be in that list if you called dir() on a string.# This means that you call `s.join()`.## To see what it does, you can call:## help(s.join)## At the top level to open the documentation for the join function.

If you run it python strings.py, you should see this output:

17
['foood', 'cake', 'cheese']
3
['cake', 'foood', 'cheese']

Lists

If you've programmed in C/C++/Java, lists are similar to arrays, except they can dynamically change in size. See the python list documentation for more information on what you can do with lists.

Open up lists.py for examples.

# Declare a list of stringsl= ["food", "cat", "bar"]
printlprintlen(l) # print the length of the listprintl[1] # print "cat"# append to the end of the listl.append("dog")
l[2] ="homer"# replace "bar" with "homer"printlprintlen(l)
# Traverse the listforsinl:
prints# Slicing a listm=list(range(20))
print"m", mprint"m[-1]", m[-1] # last elementprint"m[10:]", m[10:] # print the rest of list starting starting at index 10print"m[:10]", m[:10] # print from the beginning of the list up to but not includinx index 10print"m[5:15]", m[5:15] # print starting from 5 and up to but not including 15print"m[5:-2:3]", m[5:-2:3] # print every 3rd element, starting at index 5 and going up-to-but-not-including the second-to-last element

This should be your output: (python lists.py):

['food', 'cat', 'bar']
3
cat
['food', 'cat', 'homer', 'dog']
4
food
cat
homer
dog
m [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
m[-1] 19
m[10:] [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
m[:10] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
m[5:15] [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
m[5:-2:3] [5, 8, 11, 14, 17]

Sets

Sets are like lists, except they do not contain duplicates, and they don't contain a notion of order (e.g. if s is a set, s[0] makes no sense). See the python documentation on sets for more information.

Open up sets.py for examples.

s=set([5, 6, 7, 5, 6, 7, 1, 5, 6, 7])
printsprint"length", len(s)
foritemins:
printitemprint"is 4 in set", 4inss.add(4)
print"is 4 in set", 4insprint"sum", sum(s)

You should have this output:

set([1, 5, 6, 7])
length 4
1
5
6
7
is 4 in set False
is 4 in set True
sum 23

Dictionaries

Think of a dictionary that can map keys to values. Each key can have exactly one value. Key can be anything (immutable), and value can be anything. See the python documentation for dictionaries for more information.

Open dicts.py for examples.

d= {"cat" : 2, "tiger": 0}
d["food"] =5d["cheese"] =7d["apple"] ="orange"d[8] ="penguin"printdprintlen(d) # number of keysforkeyind:
printkey, d[key]
forkey, valueind.items():
printkey, valueprint"check if food is in d", "food"inddeld["food"]
print"check if food is in d", "food"ind

If you run it, you should get this output: (python dicts.py)

{'cheese': 7, 'apple': 'orange', 'food': 5, 'cat': 2, 'tiger': 0, 8: 'penguin'}
6
cheese 7
apple orange
food 5
cat 2
tiger 0
8 penguin
cheese 7
apple orange
food 5
cat 2
tiger 0
8 penguin
check if food is in d True
check if food is in d False

Finish Bootcamp

Go back home

Clone this wiki locally