visit
Tuples are an important data structure in Python which are quite similar to Python lists. The main difference between tuples and lists is tuples cannot be modified. Once it's created, it is fixed and unchangeable. Tuples are faster than lists, so if you know your data won't change, it's the correct way to go. Tuples are often used for iterating through a list of fixed items we know won't change.
myTuple = ("my", "new", "tuple")
print(myTuple) # ('my', 'new', 'tuple')
myTuple = "my", "new", "tuple"
print(myTuple) # ('my', 'new', 'tuple')
myTuple = ("my", "new", "tuple")
myTuple[0] = "your" # TypeError: 'tuple' object does not support item assignment
As you might expect, though, that means we can access tuple data using the syntax myTuple[0]
, to refer to the item at index 0.
Tuples may contain duplicates, so they aren't limited by uniqueness like Python sets:
myTuple = ("my", "new", "tuple", "tuple")
print(myTuple) # ('my', 'new', 'tuple', 'tuple' )
myTuple = ( ("nested", "tuple"), "my", "new", "tuple", "tuple")
As with Python sets, we can test for membership using tuples using the in
and not in
keywords. For example, below, we check if apple
is in our tuple of fruits
:
fruits = ("apple", "pear", "strawberry")
print("apple" in fruits) # True
print("apple" not in fruits) # False
tupleOne = ("one", "two")
tupleTwo = ("three", "four")
tupleThree = tupleOne + tupleTwo
print(tupleThree) # ("one", "two", "three", "four")
Since tuples are ordered like Python lists, we can also sort our tuples. However, a tuple has no method sort()
, so we have to use the sorted()
function. Why can't we use a sort()
method? Since tuples are immutable! So we have to define a new tuple using sorted()
:
myTuple = ("a", "c", "e", "b", "f", "d", "g", "z", "w", "x")
myNumberTuple = (1, 3, 5, 2, 7, 4, 6)
newTuple = sorted(myTuple)
newNumberTuple = sorted(myNumberTuple)
print(newTuple) # ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'w', 'x', 'z')
print(newNumberTuple) # (1, 2, 3, 4, 5, 6, 7)
As with list.sort()
, if you try to sort with multiple types - like integers and strings, you'll end up getting an error. Here we have to use the additional arguments of sorted()
to sort our list:
key
gives us a number that will be used to compare the list contentreverse
if set to true will reverse the order.
For example, to put all values which are b
at the start of a tuple, we could try something like this:
def isB(letter):
if(letter == "b"):
return 1
else:
return 0
myTuple = ("b", "c", "b", 5, "f", "b", 2, "z", "a", "x")
newTuple = sorted(myTuple, key=isB, reverse=True)
print(newTuple) # ['b', 'b', 'b', 'c', 5, 'f', 2, 'z', 'a', 'x']
Here we define a function isB
that is used in sorted()
to pass each item in the tuple to the function. If the item in the tuple is b
, then the order for that item is set to 1
, otherwise it's 0
. This lets us order our list based on conditions other than alphanumeric order.