Data Structures
Tuples
Tuples are effectively an
immutable
list. Once a tuple has been defined, you cannot add, update, or delete items
from it. A tuple begins and ends with parentheses ()
and items are separated
by a comma ,
Spaces don't matter here.
a = ( 1, 2, 3 )
Indexing
Like other iterable types in Python, you can index and slice tuples
a[0]
a[1]
a[::2]
Unpacking
Often used in
for
loops, you can unpack a tuple into individual variables
a, b, c = ( 1, 2, 3 )
In this case a = 1
, b = 2
, and c = 3
. Remember this pattern as it often
appears in code and documentation.
Immutability
The immutability property of a tuple is desirable under some circumstances. For example, only immutable types in Python can be hashed and only hashable types can be used as dictionary keys. For example, this is perfectly legal code
a = {
( 'StudyA', 'Subject1' ): [ 'Session1', 'Session2' ],
( 'StudyA', 'Subject2' ): [ 'Session3', 'Session4' ],
( 'StudyB', 'Subject1' ): [ 'Session5', 'Session6' ]
}
Note that you cannot hash a tuple if it contains a mutable type.
and subsequently you can retrieve an item from this dictionary using
('StudyA','Subject2')
a[( 'StudyA', 'Subject2' )]