Learn Python in One Day and Learn It Well (2015)
Appendix C: Working With Tuples
=> marks the start of the output
del
Delete the entire tuple
[Example]
myTuple = (‘a’, ‘b’, ‘c’, ‘d’)
del myTuple
print (myTuple)
=> NameError: name 'myTuple' is not defined
in
Check if an item is in a tuple
[Example]
myTuple = (‘a’, ‘b’, ‘c’, ‘d’)
‘c’ in myTuple
=> True
‘e’ in myTuple
=> False
len( )
Find the number of items in a tuple
[Example]
myTuple = (‘a’, ‘b’, ‘c’, ‘d’)
print (len(myTuple))
=> 4
Addition Operator: +
Concatenate Tuples
[Example]
myTuple = (‘a’, ‘b’, ‘c’, ‘d’)
print (myTuple + (‘e’, ‘f’))
=> (‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’)
print (myTuple)
=> (‘a’, ‘b’, ‘c’, ‘d’)
Multiplication Operator: *
Duplicate a tuple and concatenate it to the end of the tuple
[Example]
myTuple = (‘a’, ‘b’, ‘c’, ‘d’)
print(myTuple*3)
=> ('a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd')
print (myTuple)
=> (‘a’, ‘b’, ‘c’, ‘d’)
Note: The + and * symbols do not modify the tuple. The tuple stays as [‘a’, ‘b’, ‘c’, ‘d’] in both cases.