Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Besides just retrieving a single data value from a tuple, Python also allows you to retrieve a subset of
the data values. If you need to retrieve a sequential subset of data values from the tuple (called a
slice), you just use the index format [i:j], where i is the starting index value, and j is the ending
index value. Here’s an example of doing that:


>>> tuple7 = tuple6[1:3]
>>> print(tuple7)
(2, 3)
>>>

Watch Out!: Starting and Ending Tuple Slices
Notice that the first value in the new tuple is the starting index value defined for the
slice, but the ending value is the index value just before the ending index value defined
for the slice. This can be somewhat confusing. To help remember this format, when
determining a tuple slice, just use the equation i <= x < j, where x is the index
values you want to retrieve.

Finally, there’s one more format you can use for extracting data elements from a tuple, [i:j:k],
where i is the starting index value, j is the ending index value, and k is a step amount to use to
increment the index values in between the start and ending values. Here’s an example of how this
works:


Click here to view code image


>>> tuple8 = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
>>> tuple9 = tuple8[0:6:2]
>>> print(tuple9)
(1, 3, 5)
>>>

The tuple9 value consists of the data values contained in the tuple8 variable starting at index 0 ,
until index 6 , skipping every 2 index values. Thus, the resulting tuple consists of index values 0 , 2 ,
and 4 , which creates the tuple (1, 3, 5).


Working with Tuples


Since tuple values are immutable, there aren’t any Python functions available to manipulate the data
values contained in a tuple. However, there are some functions available to help you gain information
about the data contained in a tuple.


Checking Whether a Tuple Contains a Value


There are two comparison operations you can use with tuple variables to check whether a tuple
contains a specific data value.


The in comparison operator returns a Boolean True value if the specified value is contained in the
tuple data elements:


Click here to view code image


>>> if 7 in tuple8: print("It's there!")

It's there!
>>> if 12 in tuple8:
print("It's there!")
Free download pdf