Python

Python Tuples: A Complete Guide

Sponsor

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.

In this guide, we’ll cover how to use Tuples, as well as some of the methods and things you’d want to do with them. To start, let’s define a new Tuple:

myTuple = ("my", "new", "tuple") print(myTuple) # ('my', 'new', 'tuple')

You may also see tuples being defined without brackets. A list of comma separated values also automatically becomes a tuple:

myTuple = "my", "new", "tuple" print(myTuple) # ('my', 'new', 'tuple')

Trying to change a tuple, will result in an error:

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' )

Finally, tuples can also be nested, just like lists:

myTuple = ( ("nested", "tuple"), "my", "new", "tuple", "tuple")

Checking Membership using Tuples

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

Combining Tuples

Since we can’t modify tuples, if we want to make an updated version of a tuple we need to combine it. That can be done by adding them together:

tupleOne = ("one", "two") tupleTwo = ("three", "four") tupleThree = tupleOne + tupleTwo print(tupleThree) # ("one", "two", "three", "four")

Sorting a Tuple

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 which will be used to compare the list content
  • reverse 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 which 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 let’s us order our list based on conditions other than alphanumeric order.

Conclusion

Thanks for reading. You can learn more about Python data collections below:

Last Updated Saturday, 1 October 2022

More Tips and Tricks for Python

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email