Python 3home |
Introduction to Python
davidbpython.com
It's helpful to contrast these containers with lists.
It's easy to remember how to use one of these containers by considering how they differ in behavior.
A tuple is an immutable, ordered sequence of values.
var2 = (1, 2, 3, 'a', 'b') # initialize a tuple of values
Subscripting allows us to read individual items from a tuple.
mytuple = (1, 2, 3, 'a', 'b') # initialize a tuple of values
xx = mytuple[3] # 'a'
Note that as with lists, indexing starts at 0, so index 1 is the 2nd item, index 2 is the 3rd item, etc.
Slicing a tuple returns a new tuple.
var2 = (1, 2, 3, 'a', 'b') # initialize a tuple of values
subtuple1 = var2[0:3] # (1, 2, 3)
subtuple2 = var2[2:4] # (3, 'a')
subtuple3 = var2[3:] # ('a', 'b')
Remember the rules of slicing, which are the same as lists and strings:
Concatenation works in the same way as with lists and strings.
var = ('a', 'b', 'c')
var2 = ('d', 'e', 'f')
var3 = var + var2 # ('a', 'b', 'c', 'd', 'e', 'f')
Ex. 5.12
A set is an unordered, unique collection of values.
myset = set() # initialize an empty set (note that empty
# curly braces are reserved for dicts)
myset = {'a', 9999, 4.3, 'a'} # initialize a set with items
print(myset) # {9999, 4.3, 'a'}
The set changes in place; any duplicate item will be ignored.
myset = set() # initialize an empty set
myset.add(4.3) # note well! we do not assign back to myset
myset.add('a')
myset.add('a')
print(myset) # {'a', 4.3} (order is not
# necessarily maintained)
Here are len() and in with a tuple.
# get the length of a set or tuple (compare to len() of a list or string)
myset = {1, 2, 3, 'a', 'b'}
yy = len(myset) # 5
# test for membership in a set or tuple
mytuple = (1, 2, 3, 'a', 'b')
if 'b' in mytuple: # bool, True
print("'b' can be found in mytuple")
print('b' in mytuple) # "True": the 'in' operator
# actually returns True or False
The 'for' loop allows us to traverse a set or tuple and work with each item.
mytuple = (1, 2, 3, 'a', 'b') # could also be a set here
for var in mytuple:
print(var) # prints 1, then 2, then 3,
# then a, then b
These functions also work as they do with lists.
Whether a set or tuple, these operations work in the same way.
mytuple = (1, 3, 5, 7, 9) # initialize a tuple
myset = {1, 3, 5, 7, 9} # initialize a set
print(len(mytuple)) # 5 (count of items)
print(sum(myset)) # 25 (sum of values)
print(min(myset)) # 1 (smallest value)
print(max(mytuple)) # 9 (largest value)
Regardless of type, sorted() returns a list of sorted values.
mytuple = (4, 9, 1.2, -5, 200, 20) # could also be a set here
smyl = sorted(mytuple) # [-5, 1.2, 4, 9, 20, 200]
Ex. 5.13
The set's duplicate elimination behavior gives us certain advantages.
As we saw, sets have 2 important characteristics:
How can we use a set?