Using Tuples


hexStringChars = ('A', 'B','C', 'D', 'E', 'F') hexStringNums = ('1', '2', '3', '4', '5', '6',\                  '7', '8', '9','0') hexStrings = ["1FC", "1FG", "222", "Ten"] for hexString in hexStrings:     for x in hexString:         if ((not x in hexStringChars) and             (not x in hexStringNums)):             print hexString+ \                 " is not a hex string."             break tupleList = list(hexStringChars) listTuple = tuple(hexStrings)

When working with lists in Python, it is a good idea to understand the place that tuples have. Tuples are similar to lists in that they are index-based collections of objects. There is one major difference, however. The contents of a tuple cannot be modified after the tuple is initially defined. Tuples are defined similar to lists except that they are encased in parentheses instead of in brackets.

Tuples are very valuable because they are much faster to access and use than lists. For example, the in operation works much faster on a tuple to determine whether an object exists in the tuple. Tuples are also valuable because you know the data contained in them will always remain static. Tuples can also be used as keys for dictionaries where lists cannot.

Note

The tuples must be made up of strings and/or integers and cannot contain lists to be considered immutable and used as dictionary keys.


Tuples can be converted into lists by using the list() function. The list function returns a copy of the tuple in an editable list form. In the same way, lists can be converted into tuples using the tuple() function. The tuple function returns a copy of the list in tuple form, effectively giving you a frozen snapshot of the list.

hexStringChars = ('A', 'B','C', 'D', 'E', 'F') hexStringNums = ('1', '2', '3', '4', '5', '6',\                   '7', '8', '9', '0') hexStrings = ["1FC", "1FG", "222", "Ten"] for hexString in hexStrings:     for x in hexString:         if ((not x in hexStringChars) and             (not x in hexStringNums)):             print hexString +\                 " is not a hex string."             break #Tuple to list tupleList = list(hexStringChars) print tupleList #List to tuple listTuple = tuple(hexStrings) print listTuple


tuple.py

1FG is not a hex string. Ten is not a hex string. ['A', 'B', 'C', 'D', 'E', 'F'] ('1FC', '1FG', '222', 'Ten')


Output from tuple.py code



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net