Home Python Page 2 - Tuples and Other Python Object Types

Tuples - Python

In this conclusion to a four-part article series on Python object types, we will finish our discussion of dictionaries, move on to tuples, and cover related material. This article is excerpted from chapter four of the book Learning Python, Third Edition, written by Mark Lutz (O'Reilly, 2008; ISBN: 0596513984). Copyright © 2008 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Rating:  / 4
February 05, 2009

SEARCH DEV SHED

TOOLS YOU CAN USE

The tuple object (pronounced “toople” or “tuhple,” depending on who you ask) is roughly like a list that cannot be changed—tuples are sequences, like lists, but they are immutable, like strings. Syntactically, they are coded in parentheses instead of square brackets, and they support arbitrary types, nesting, and the usual sequence operations:

>>> T = (1, 2, 3, 4)            # A 4-item tuple
>>> len(T)                       # Length
4

>> T + (5, 6)                   # Concatenation
(1, 2, 3, 4, 5, 6)

>>> T[0]                        # Indexing, slicing, and more
1

The only real distinction for tuples is that they cannot be changed once created. That is, they are immutable sequences:

>>> T[0] = 2                 # Tuples are immutable

...error text omitted...
TypeError: 'tuple' object does not support item assignment

Why Tuples?

So, why have a type that is like a list, but supports fewer operations? Frankly, tuples are not generally used as often as lists in practice, but their immutability is the whole point. If you pass a collection of objects around your program as a list, it can be changed anywhere; if you use a tuple, it cannot. That is, tuples provide a sort of integrity constraint that is convenient in programs larger than those we can write here. We’ll talk more about tuples later in the book. For now, though, let’s jump ahead to our last major core type, the file.

Files

File objects are Python code’s main interface to external files on your computer. They are a core type, but they’re something of an oddball—there is no specific literal syntax for creating them. Rather, to create a file object, you call the built-in open function, passing in an external filename as a string, and a processing mode string. For example, to create an output file, you would pass in its name and the 'w' processing mode string to write data:

>>> f = open('data.txt',
'w')
# Make a new file in output mode
>>> f.write('Hello\n')          # Write strings of bytes to it
>>> f.write('world\n')

>>> f.close()                  #  Close to flush output buffers to disk

This creates a file in the current directory, and writes text to it (the filename can be a full directory path if you need to access a file elsewhere on your computer). To read back what you just wrote, reopen the file in 'r' processing mode, for reading input (this is the default if you omit the mode in the call). Then read the file’s content into a string of bytes, and display it. A file’s contents are always a string of bytes to your script, regardless of the type of data the file contains:

>>> f = open('data.txt')             # 'r' is the default processing mode
>>> bytes
'Hello\nworld\n'

>>> print bytes                    # Print interprets control characters

Hello
world

>>> bytes.split()                    # File content is always a string

['Hello', 'world']

Other file object methods support additional features we don’t have time to cover here. For instance, file objects provide more ways of reading and writing (readaccepts an optional byte size,readlinereads one line at a time, and so on), as well as other tools (seek moves to a new file position). We’ll meet the full set of file methods later in this book, but if you want a quick preview now, run adircall on the wordfile(the name of the file data type), and ahelpon any of the names that come back:

>>> dir(file)

['__class__', '__delattr__', '__doc__', '__enter__', '__exit__',
'__getattribute__', '__hash__', '__init__', '__iter__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__',  '__setattr__', '__str__',
'close', 'closed', 'encoding', 'fileno', 'flush', 'isatty', 'mode',
'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

>>> help(file.seek)

...try it and see...

Other File-Like Tools

The open function is the workhorse for most file processing you will do in Python. For more advanced tasks, though, Python comes with additional file-like tools: pipes, fifos, sockets, keyed-access files, object persistence, descriptor-based files, relational and object-oriented database interfaces, and more. Descriptor files, for instance, support file locking and other low-level tools, and sockets provide an interface for networking and interprocess communication. We won’t cover many of these topics in this book, but you’ll find them useful once you start programming Python in earnest.

 >>> More Python Articles          >>> More By O'Reilly Media