Lists
One of the most useful built-in types in Python is the list. A list, like a string,, is a sort of sequence. But lists are represented as sequences inside square brackets, [], and the elements are separated by commas. List elements are accessed by their index, that is, their position in the list, starting at 0. Unlike similar classes in some other languages, Python lists can take any objects for elements, including a mix of objects of different types.
Try this: create a string containing tabs, which are represented as \t in a string, and make a list by splitting on the tab characters.
List elements are accessed via their position in the list, counting from zero (the first list element is at index 0). Lists can be sliced like myList[x:y]
; this returns a list that starts at element x
and ends before element y
. Omitting the entry before the : means "starting at the beginning of the list"; and omitting the entry after the :
means "ending at the end of the list".
Unlike strings, which are immutable sequences (that we can process to produce new strings), lists are mutable. (We demonstrated that above, by changing fum
to False
.) But a list variable really just holds a reference to the underlying compound object: you need to be careful when you copy a list!
A partial solution is to use the list constructor or the slice operation to make a new list via a shallow copy. But if the list contains other compound types then they won't be independently copied:
The way to make a completely independent copy of a list (or any compound object in Python)—a deep copy—is to use the the copy.deepcopy()
method. Unless you are absolutely sure that a shallow copy is sufficient or desired, use copy.deepcopy()
to make copies of compound objects, as the errors which can occur from shallow copies are often frustrating to debug.
Mini-exercise: list and str
- Construct a list of 10 numbers [Hint: use list() as a constructor, with a call to range() as input; this technique works in both Python 2 and 3]
- Write a for-loop to print the first five items in the list [Hint: use slicing]
- Print the maximum number in the list
- Repeat the above for an arbitrary string of 10 characters