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

Prereqs

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.
print len(s)

# split string by spaces, return list of words
words = s.split()
print words
print len(words)

# keyfunc and keyfunc2 are exactly the same
# lambdas are just syntactic sugar to allow you
# to declare one-liner functions.
keyfunc = lambda word : len(word)

def keyfunc2(word):
    return len(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)
print words_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.

# Declare a list of strings
l = ["food", "cat", "bar"]
print l
print len(l) # print the length of the list
print l[1] # print "cat"

# append to the end of the list
l.append("dog")
l[2] = "homer" # replace "bar" with "homer"
print l
print len(l)

# Traverse the list
for s in l:
    print s

# Slicing a list
m = list(range(20))
print "m", m
print "m[-1]", m[-1] # last element
print "m[10:]", m[10:] # print the rest of list starting starting at index 10
print "m[:10]", m[:10] # print from the beginning of the list up to but not includinx index 10
print "m[5:15]", m[5:15] # print starting from 5 and up to but not including 15
print "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]
Clone this wiki locally