Based on lecture materials by Milad Fatenejad, Joshua R. Smith, Will Trimble, and Anthony Scopatz
Python would be a fairly useless language if it weren't for the compound data types. The main two are lists and dictionaries, but we'll discuss sets and tuples as well. I'll also go over reading text data from files.
In [ ]:
voltages = [-2.0, -1.0, 0.0, 1.0, 2.0]
currents = [-1.0, -0.5, 0.0, 0.5, 1.0]
voltages is of type list:
In [ ]:
type(voltages)
Python lists are indexed from zero. Therefore, to find the value of the first item in voltages
:
In [ ]:
voltages[0]
And to find the value of the third item
In [ ]:
voltages[2]
Lists can be indexed from the back using a negative index. This expression gives us the last element of currents
:
In [ ]:
currents[-1]
and the next-to-last
In [ ]:
currents[-2]
You can "slice" items from within a list. Lets say we wanted the second through fourth items from voltages
In [ ]:
voltages[1:4]
Slicing lists from the beginning until a given index or from a given index to the end
is so common a task that it has a shortcut. If you omit the index to the left of
the colon, it is interpreted as 0. If you omit the index to the right of the colon,
it is interpreted as len(<list>)
. So this expression takes all the elements starting
from the third and continuing to the end of the list:
In [ ]:
voltages[2:]
Note: when taking slices, the elements returned include the starting index but exclude the final index.
In [ ]:
voltages[0:len(voltages)] # this expression gives the entire list.
voltages[:] # and this is the shortcut for the above.
The Python documentation--An informal Introduction to Python contains more examples and more details about how to create and access instances of this utilitarian data structure.
In [ ]:
dir(list)
One useful method is append. Lets say we want to stick the following data on the end of both our lists.
voltages:
3.0
4.0
currents:
1.5
2.0
If you want to append items to the end of a list, use the append method.
In [ ]:
print voltages
voltages.append(3.0)
print voltages
In [ ]:
print voltages
voltages.append(4.0)
print voltages
In [ ]:
voltages
You can see how that approach might be tedious in certain cases. If you want to concatenate a list onto the end of another one, use extend.
In [ ]:
print currents
currents.extend([1.5, 2.0])
print currents
In [ ]:
currents
In [ ]:
len(voltages)
In [ ]:
data_list = ["experiment: current vs. voltage",
"run", 47,
"temperature", 372.756,
"current", [-1.0, -0.5, 0.0, 0.5, 1.0],
"voltage", [-2.0, -1.0, 0.0, 1.0, 2.0],
]
In [ ]:
print data_list
We've got strings, ints, floats, and even other lists in there.
Something that might cause you headaches in the future is how python deals with assignment of one variable to another. When you set a variable equal to another, both variables point to the same thing. Changing the first one ends up changing the second. Be careful about this fact.
In [ ]:
a = [1, 2]
In [ ]:
b = a
In [ ]:
a.append(10)
In [ ]:
b
To actually make a copy of a list or a dict, use the list()
and dict()
builtin methods.
In [ ]:
a = [1, 2]
b = list(a)
a.append(10)
print a
print b
As a diagnostic tool, if you are ever uncertain if an assignment is making two different variables,
you can test whether two variables are actually distinct with the is
operator:
In [ ]:
a is b
There's a ton more to know about lists, but let's press on. Check out Dive Into Python or the Python documentation for more info.
In [ ]:
tup = ("red", "white", "blue")
In [ ]:
type(tup)
You can slice and index the tuple exactly like you would a list. Tuples are used in the inner workings of python, and a tuple can be used as a key in a dictionary, whereas a list cannot as we will see in a moment.
See if you can retrieve the third element of tup:
In [ ]:
In [ ]:
fruit = {"apple", "banana", "pear", "banana"}
You have to use a list to create a set.
Since sets contain only unique items, there's only one banana in the set fruit.
You can do things like intersections, unions, etc. on sets just like in math. Here's an example of an intersection of two sets (the common items in both sets).
In [ ]:
bowl1 = {"apple", "banana", "pear", "peach"}
In [ ]:
bowl2 = {"peach", "watermelon", "orange", "apple"}
In [ ]:
bowl1 & bowl2
In [ ]:
bowl1 | bowl2
You can read more in the sets documentation.
A Python dictionary is a unordered collection of key-value pairs. Dictionaries are by far the most important data type in Python. The key is a way to name the data, and the value is the data itself. Here's a way to create a dictionary that contains all the data in our data.dat file in a more sensible way than a list.
In [ ]:
data_dict = {"experiment": "current vs. voltage",
"run": 47,
"temperature": 372.756,
"currents": [-1.0, -0.5, 0.0, 0.5, 1.0],
"voltages": [-2.0, -1.0, 0.0, 1.0, 2.0],
}
In [ ]:
print data_dict
This model is clearly better because you no longer have to remember that the run number is in the second position of the list, you just refer directly to "run":
In [ ]:
data_dict["run"]
If you wanted the voltage data list:
In [ ]:
data_dict["voltages"]
Or perhaps you wanted the last element of the current data list
In [ ]:
data_dict["currents"][-1]
Once a dictionary has been created, you can change the values of the data if you like.
In [ ]:
data_dict["temperature"] = 3275.39
You can also add new keys to the dictionary. Note that dictionaries are indexed with square braces, just like lists--they look the same, even though they're very different.
In [ ]:
data_dict["user"] = "Johann G. von Ulm"
Dictionaries, like strings, lists, and all the rest, have built-in methods. Lets say you wanted all the keys from a particular dictionary.
In [ ]:
data_dict.keys()
also, values
In [ ]:
data_dict.values()