Facebook SDK

Tuesday, April 1, 2014

Beginning Python Tutorial (Part 6)

Python Tuples

The final built-in data type is the tuple. Python tuples work exactly like Python lists except they are immutable, i.e. they can't be changed in place. They are normally written inside parentheses to distinguish them from lists (which use square brackets), but as you'll see, parentheses aren't always necessary. Since tuples are immutable, their length is fixed. To grow or shrink a tuple, a new tuple must be created.
Here's the list of common operations for tuples:
  • () An empty tuple
  • t1 = (0, ) A one-item tuple (not an expression)
  • t2 = (0, 1, 2, 3) A four-item tuple
  • t3 = 0, 1, 2, 3 Another four-item tuple (same as prior line)
  • t3 = ('abc', ('def', 'ghi')) Nested tuples
  • t1[n], t3[n][j] Index
  • t1[i:j]slice
  • len(tl) length
  • t1 + t2 Concatenate
  • t2 * 3 repeat
  • for × in t2Iteration
  • 3 in t2 membership
The second entry shows how to create a one item tuple. Since parentheses can surround expressions, you have to show Python when a single item is actually a tuple by placing a comma after the item. The fourth entry shows a tuple without parentheses; this form can be used when a tuple is unambiguous. However, it's easiest to just use parentheses than to figure out when they're optional.
The biggest thing to remember is that standard operations like slice and iteration return new tuple objects. In my opinion, I'd use lists for everything except when I don't want a collection to change. It cuts down on the number of collections to think about.
Well, that's it for this session. The next, and final, object type to learn about are Python files which will be discussed in the next tutorial. Thanks for reading.

No comments: