Working with Tuples
As previously
mentioned, a tuple is a collection used to create complex lists, in which you
can embed one tuple within another. This embedding lets you create hierarchies
with tuples. A hierarchy could be something as simple as the directory listing
of your hard drive or an organizational chart for your company. The idea is
that you can create complex data structures using a tuple.
Tuples are
immutable, which means you can’t change them. You can create a new tuple with
the same name and modify it in some way, but you can’t modify an existing
tuple. Lists are mutable, which means that you can change them. So, a tuple can
seem at first to be at a disadvantage, but immutability has all sorts of
advantages, such as being more secure as well as faster. In addition, immutable
objects are easier to use with multiple processors.
The two biggest
differences between a tuple and a list are that a tuple is immutable and allows
you to embed one tuple inside another. The following steps demonstrate how you
can interact with a tuple in Python.
Open a Python Shell window.
You see the
familiar Python prompt.
Type MyTuple=(“Red”, “Blue”, “Green”) and
press Enter. Python creates a tuple containing three strings.
Type MyTuple and press Enter.
You see the
content of MyTuple, which is three strings. Notice that the entries use single
quotes, even though you used double quotes to create the tuple. In addition,
notice that a tuple uses parentheses rather than square brackets, as lists do.
Type dir(MyTuple)
and press Enter.
Python presents a
list of functions that you can use with tuples. Notice that the list of functions
appears significantly smaller than the list of functions provided with lists in
previous post. The count() and index() functions are present.
However,
appearances can be deceiving. For example, you can add new items using the
__add__() function. When working with Python objects, look at all the entries
before you make a decision as to functionality.
5. Type MyTuple=MyTuple.__add__((“Purple”,)) and press Enter.
This code adds a
new tuple to MyTuple and places the result in a new copy of MyTuple. The old
copy of MyTuple is destroyed after the call.
The __add__()
function accepts only tuples as input. This means that you must enclose the
addition in parentheses. In addition, when creating a tuple with a single
entry, you must add a comma after the entry, as shown in the example. This is
an odd Python rule that you need to keep in mind or you’ll see an error message
similar to this one:
TypeError: can
only concatenate tuple (not "str") to tuple
Type MyTuple and press Enter.
The addition to
MyTuple appears at the end of the list. Notice that it appears at the same
level as the other entries.
Type MyTuple=MyTuple.__add__((“Yellow”,
(“Orange”, “Black”))) and press Enter.
This step adds
three entries: Yellow, Orange, and Black. However, Orange and Black are added
as a tuple within the main tuple, which creates a hierarchy. These two entries
are actually treated as a single entry within the main tuple.
You can replace
the __add__() function with the concatenation operator. For example, if you
want to add Magenta to the front of the tuple list, you type MyTuple=("Magenta",) + MyTuple.
Type MyTuple[4] and press Enter.
Python displays a
single member of MyTuple, Orange. Tuples use indexes to access individual
members, just as lists do. You can also specify a range when needed. Anything
you can do with a list index you can also do with a tuple index.
Type MyTuple[5] and press Enter.
You see a tuple
that contains Orange and Black. Of course, you might not want to use both
members in tuple form.
Tuples do contain
hierarchies on a regular basis. You can detect when an index has returned
another tuple, rather than a value, by testing for type. For example, in this
case, you could detect that the sixth item (index 5) contains a tuple by typing
type(MyTuple[5]) == tuple. The output would be True in this case.
Type MyTuple[5][0] and press Enter.
At this point, you
see Orange as output. The indexes always appear in order of their level in the
hierarchy.
Using a
combination of indexes and the __add__() function (or the concatenation
operator, +), you can create flexible applications that rely on tuples. For
example, you can remove an element from a tuple by making it equal to a range
of values. If you wanted to remove the tuple containing Orange and Black, you
type MyTuple=MyTuple[0:5].
Working with Dictionaries
A Python
dictionary works just the same as its real-world counterpart — you create a key
and value pair. It’s just like the word and definition in a dictionary. As with
lists, dictionaries are mutable, which means that you can change
them as needed.
The main reason to use a dictionary is to make information lookup faster. The
key is always short and unique so that the computer doesn’t spend a lot of time
looking for the information you need.
The following
sections demonstrate how to create and use a dictionary. When you know how to
work with dictionaries, you use that knowledge to make up for deficiencies in
the Python language. Most languages include the concept of a switch statement,
which is essentially a menu of choices from which one choice is selected.
Python doesn’t include this option, so you must normally rely on if...elif
statements to perform the task. (Such statements work, but they aren’t as clear
as they could be.)
0 comments:
Post a Comment