Math 152: Intro to Mathematical Software
2017-01-18
Kiran Kedlaya
**Lecture 4: Introduction to Python (part 2) **
Administrivia:
Peer evaluations for Homework 1 due Thursday, January 19, at 8pm
Homework 2 due Tuesday, January 24 at 8pm. Remember, put all your work in the "assignments/2017-01-24" folder; it will be collected automatically after the deadline passes.
Guest lecturer Friday, January 20: William Stein, the creator of SageMath and SageMathCloud.
Today's topic is composite data types (lists, tuples, dicts).
Lists
A list is a Python type consisting of an ordered list of other objects. This is similar to the concept of an array in other programming languages; however, in Python the objects of a list can be of different types (e.g., numbers and strings can be combined in the same list).
If l
is a list, then the objects of the list can be retrieved as l[0], l[1], ...
; note that the first index is 0, not 1. The last items in a list can be retrieved as l[-1], l[-2], ...
.
Here are some examples of operations on lists.
Many of the available operations on lists, and on other Python objects, are accessed using a slightly different syntax than the one used so far. Look at these examples.
These kinds of functions are specific to a certain type of object, in this case lists; they are called methods of the object class. This is a symptom of the fact that Python is an object-oriented programming language; we will see later how Sage takes advantage of this architecture to implement mathematical objects.
In the meantime, I point out two ways to find out more about the methods associated to a particular class of objects.
Use tab-completion: type
l.
and hit the Tab key to see a list of methods associated tol
. If you have typed some letters after the period before hitting Tab, you'll only get objects whose names match the initial string you typed.Look at the page from the Python documentation corresponding to the type. For example, for lists this page is https://docs.python.org/2/tutorial/datastructures.html.
List Comprehensions
Mathematicians are fond of constructing sets out of other sets. Python offers a similar syntax:
et cetera.
You can typically rewrite a list comprehension as a for loop (or nested for loops).
KEY INSIGHT: The order of the for loops and the if are exactly the same as in the list comprehension.
Try this now:
Construct the following list using a list comprehension and the if/else exercise function my_sign
you wrote last time:
If you have time, do the same but using a for loop.
Warning: lists are mutable
Python Lists
There is a serious subtlety with how Python lists works. This is a frequent source of errors for new Python users.
In Python, objects are copied by reference, not by value. That is, when you perform the assignment b = a
, Python does not assign a copy of the value of a
to the new variable b
; rather, a
and b
are both references to the same object in memory. (This is different from MATLAB, for example.)
This is already true for basic objects like integers, but isn't really an issue.
By contrast, basic operations on lists change the original list, rather than creating a new one. This can lead to unexpected side effects.
For comparison, here is an example of arrays in Matlab. (Technically, this is not Matlab but Octave, an open-source clone of MATLAB which is available from within Sage.)
a =
1 2 3
b =
5 2 3
And R (1-based and copy by value):
Here's what happens in Javascript (0-based and copy by reference):
And in Julia (1-based and copy by reference!):
a =[5,2,3]
b =[5,2,3]
The point is that different programming languages make very subtle and different design choices. And that's all they are -- choices. One choices really is better for some purposes and worse for other purposes.
The copy by reference choice of Python makes lists potentially subtle. For example:
Now what the heck is w equal to? (Wait until lots of people in class think this through.)
Moral: Just because something prints out at [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
doesn't mean you know what that something is! In Python, things can be very subtle.
Don't judge an object by its cover (how it prints).
If you don't get this point, you might hate Python. If you do, you might start to see huge power and flexibility in what Python offers... and understand why Python might be the most popular programming language in data science, which is itself a very popular emerging field.
Shallow and deep copies.
Let's try the copy module from Python's standard library: https://docs.python.org/2/library/
MORAL: Python is a real programming language designed by software engineers. It's not a special-purpose math-only language, and it respects deeper, and more powerful, subtle (and possibly confusing) ideas from programming.
Some more about data structures: tuples, dicts, sets
tuples
Like Python lists, except you use parens instead of square brackets
You can't change the number of entries or what they reference. However, you might be able to change the referenced thing itself.
Try this now: Write a function that takes as input a tuple and returns the sorted version of the tuple.