Since the Crash Course book will be our primary reference for this tutorial, you should always start by reading the book first. The book will give you a quick but comprehensive overview of the topics we are going to study. This allows me to be lazy and not have to write up extensive lecture notes. What I will be doing in class is showing some additional examples. As we go along those examples will often be longer and more involved than the basic examples in the book. I will be focusing most of my effort on cooking up those longer examples and documenting them in the lecture notes.
Today's topic is lists in Python. You should start by reading chapters 3 and 4 in the text.
The book gives lots of good examples to illustrate what you can do with lists and iteration. Here are some additional examples I showed in class to supplement the text.
The first example is a file simple_lists.py
that demonstrates the most basic aspects of working with lists.
# A simple list of numbers example = [2,10,3,5] # Access elements with bracket notation print(example[1]) print(example[-1]) # Add new elements with append example.append(7) print(example) # Remove elements with remove example.remove(10) print(example) # Slicing a list middle = example[1:4] print(middle)
The second example file, iteration.py
, shows some basic iteration examples.
# Using range to construct a list example = list(range(2,20,2)) # Iterating over a list for n in example: print(n/2) # Doing more than one thing squares = [] for n in example: m = n*n squares.append(m) print(squares) # List comprehensions squares = [n*n for n in example] print(squares)
The third example is a file tuples.py
that shows some basic operations with tuples.
# Create a pair of tuples pt1 = (-5,4) pt2 = (2,3) # Use bracket notation to access parts of a tuple print(pt1[0]) # Things you can't do with a tuple pt1[0] = -6 pt1.append(-2) pt3 = pt1 + pt2