Tuples Immutable Sequences in python at codelent
Tuples are sequences, just like lists. The only difference is that tuples can’t be changed.5 (As you
may have noticed, this is also true of strings.) The tuple syntax is simple—if you separate some
values with commas, you automatically have a tuple:
>>> 1, 2, 3
(1, 2, 3)
As you can see, tuples may also be (and often are) enclosed in parentheses:
>>> (1, 2, 3)
(1, 2, 3)
The empty tuple is written as two parentheses containing nothing:
>>> ()
()
5. There are some technical differences in the way tuples and lists work behind the scenes, but you probably
won’t notice it in any practical way. And tuples don’t have methods the way lists do. Don’t ask me why.
So, you may wonder how to write a tuple containing a single value. This is a bit peculiar—
you have to include a comma, even though there is only one value:
>>> 42
42
>>> 42,
(42,)
>>> (42,)
(42,)
The last two examples produce tuples of length one, while the first is not a tuple at all. The
comma is crucial. Simply adding parentheses won’t help: (42) is exactly the same as 42. One
lonely comma, however, can change the value of an expression completely:
>>> 3*(40+2)
126
>>> 3*(40+2,)
(42, 42, 42)
The tuple Function
The tuple function works in pretty much the same way as list: it takes one sequence argument
and converts it to a tuple.6 If the argument is already a tuple, it is returned unchanged:
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple((1, 2, 3))
(1, 2, 3)
Basic Tuple Operations
As you may have gathered, tuples aren’t very complicated—and there isn’t really much you can
do with them except create them and access their elements, and you do this the same as with
other sequences:
>>> x = 1, 2, 3
>>> x[1]
2
>>> x[0:2]
(1, 2)
As you can see, slices of a tuple are also tuples, just as list slices are themselves lists.
Like list, tuple isn’t really a function—it’s a type. And, as with list, you can safely ignore this for now.
Function Description
cmp(x, y) Compares two values
len(seq) Returns the length of a sequence
list(seq) Converts a sequence to a list
max(args) Returns the maximum of a sequence or set of arguments
min(args) Returns the minimum of a sequence or set of arguments
reversed(seq) Lets you iterate over a sequence in reverse
sorted(seq) Returns a sorted list of the elements of seq
tuple(seq) Converts a sequence to a tuple
0 comments:
Post a Comment