Once we have variables, that is, individual named object references to objects of particular types, it is natural to want to have entire collections of object references. Python's standard collection types hold object references, so they can, in effect, hold collections of any type of object. Another consequence of collections using object references is that they can refer to objects of different types: They are not restricted to holding items that are all of a single type.
The built-in collection types are tuple, list, dict (dictionary), set, and frozenset. All except tuple and frozenset are mutable, so items can be added and deleted from lists, dictionaries, and sets. Some additional mutable collection types are provided in the collections module.*
Python has one collection type in its standard library that does not hold object references; instead, it holds numbers of a specified type. This is the array type and it is used in situations where large numbers of numbers need to be stored and processed as efficiently as possible.
In this section, we will look at Python's built-in collection types. Tuples
String A tuple is an ordered sequence of zero or more object references. Like strings slicing (and as we will see shortly, like lists), tuples support sequence functions such 22 ■a as len() as well as the same slicing syntax that we saw earlier. This makes it really easy to extract items from a tuple. However, tuples are immutable so we cannot replace or delete any of their items. If we want to be able to modify an ordered sequence, we simply use a list instead of a tuple; or if we already have a tuple but want to modify it, we just convert it to a list and then apply our changes.
We have already had some informal exposure to tuples; for example, some of our interactions in IDLE produced results that were wrapped up as tuples, and we also used tuples to provide multiple arguments to the % operator.
Here are some examples that show how to construct tuples:
>>> empty = () >>> type(empty) <type 'tuple'> >>> one = ("Canary")
★The Qt library provides its own rich set of container classes for C++, but these are not available in PyQt, and in any case, Python's own collection classes are perfectly good to use.
>>> type(one) <type 'str'> >>> one = ("Canary",) >>> type(one) <type 'tuple'>
Creating an empty tuple is simple, but for a one item tuple, we must use a comma to distinguish it from a parenthesized expression:
>>> things = ("Parrot", 3.5, u"\u20AC") >>> type(things) <type 'tuple'>
Tuples can hold items of any type; here we have str, float, and unicode items. It is also possible to drop the parentheses for tuples that have at least two items and where the meaning is unambiguous:
>>> items = "Dog", 99, "Cow", 28 >>> type(items) <type 'tuple'>
Tuples can be arbitrarily nested and can be sliced, as these examples show:
>>> names = "Albert", "Brenda", "Cecil", "Donna" >>> names[:3]
We create a tuple of names, then take a slice of the first three items, and then look at the item at index position 1. Like all Python sequences, the first item is at position 0:
>>>names = names, names, "Bernadette", names, names >>> names
('Albert', 'Brenda', 'Bernadette', 'Cecil', 'Donna')
Now we have changed the names tuple to refer to a new tuple with an extra item in the middle. It might be tempting to write names[:1] instead of names, names, and similarly names[2:] for the last two names, but if we did so we would end up with a three-item tuple:
(('Albert', 'Brenda'), 'Bernadette', ('Cecil', 'Donna'))
This is because when we use slicing on a tuple the slices are always tuples themselves.
('Albert', 'Brenda', 'Bernadette', 'Cecil', 'Donna') >>> names = names[:4]
Here, we have, in effect, chopped off the last name by taking a tuple of the first 4 items, that is, those with index positions 0,1,2, and 3. In slicing, the first number is the first index and this item is included in the result, and the second number is the last index and this item is excluded from the result.
('Albert', 'Brenda', 'Bernadette', 'Cecil') >>> names = names[:-1] >>> names
Another way of chopping off the last item is to index from the end; this way we don't have to know what the length of the tuple is. But if we want to know the length we can use the len() function:
>>> pets = (("Dog", 2), ("Cat", 3), ("Hamster", 14)) >>> len(pets) 3
(('Dog', 2), ('Cat', 3), ('Hamster', 14)) >>> pets 14
>>> pets[0:2] ('Cat', 3) >>> pets ('Cat', 3)
Tuples can be nested and items accessed using as many square brackets as necessary.
Any sequence can be given to the tuple constructor to create a tuple. For example:
Tuples are useful when we need fixed ordered collections of objects. They are also used as arguments to some functions and methods. For example, starting with Python 2.5, the str.endswith() method accepts either a single string argument (e.g., ".png") or a tuple of strings (e.g., (".png", ".jpg", ".jpeg")).
Was this article helpful?
Discover How You Can Quickly And Easily Dominate Google and YouTube... With Simple Cash Generating Videos. Did you know that YouTube is the second largest search website on the entire Internet? YouTube gets more daily searches than Bing and Yahoo. In fact, there is only one search engine that gets more action.