FANDOM


A tuple is a collection and iterable which is ordered and unchangeable.

SyntaxEdit

This is how you create a tuple:

aTuple = ("Thing01", "Thing02", "Thing03")
print(aTuple)

# Returns : 
('Thing01', 'Thing02', 'Thing03')

You can access items in a tuple using number indexes :

print(aTuple[2])

# Returns:
Thing03

The difference between lists and tuplesEdit

  • Tuples are immutable (cannot change the values in place) where lists are mutable (can be changed in place).
  • Syntax :
tupple_colours = ('red', 'blue', 'green')
list_colours = ['red', 'blue', 'green']
  • Tuples do not need to be copied, since tuples are immutable.
  • Tuples are smaller in size than lists.
  • Tuples are heterogeneous whereas lists are homogeneous. Meaning that different data can be stored in a single tuple while lists must have all the same data types stored in them.
  • Lists are for varying length, whereas tuples have fixed length.
  • Tuples show structure where lists show order.
  • Tuples are comparable and hashable so we can sort lists of them and use tuples as key values in dictionaries. (hashable: A type that has a hash function. Immutable types like integers, floats, and strings are hashable; mutable types like lists and dictionaries are not.)
  • Tuples can be used as values in sets, lists can not.

Tuples as dictionary keysEdit

Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values like strings, numbers, and other tuples). E.g :

tupleDict = {('this', 'is'): 15,
             ('an', 'example'): 19,
             ('tupleDict'): 24}

Lists can never be used as dictionary keys, because lists are not immutable. E.g :

listDict = {['this', 'is']: 15,
            ['an', 'example']: 19,
            ['tupleDict']: 24}

# Returns:
TypeError: unhashable type: 'list'

Tuples as values in setsEdit

Tuples can be used as values in sets :

tupleSet = {('this', 'is'),
            ('an', 'example'),
            ('example', 'snippet')}
print(tupleSet)
print(type(tupleSet))

# Returns: 
{('example', 'snippet'), ('an', 'example'), ('this', 'is')}
<class 'set'>

Lists can not :

listSet = {['this', 'is'],
           ['an', 'example'],
           ['example', 'snippet']}

# Returns:
TypeError: unhashable type: 'list'

ReferencesEdit

Python Tuples

Difference between lists and tuples in Python?

Python Learn: Tuples

What advantages do tuples have over lists?

Community content is available under CC-BY-SA unless otherwise noted.