06 Tuples
06 Tuples
1 Tuples
In Python tuples are very similar to lists, however, unlike lists they are immutable meaning they
can not be changed. You would use tuples to present things that shouldn’t be changed, such as
days of the week, or dates on a calendar.
In this section, we will get a brief overview of the following:
1.) Constructing Tuples
2.) Basic Tuple Methods
3.) Immutability
4.) When to Use Tuples
You’ll have an intuition of how to use tuples based on what you’ve learned about lists. We can
treat them very similarly with the major distinction being that tuples are immutable.
[5]: 3
# Show
t
[10]: ('one', 2)
1
[4]: 'one'
[16]: 2
[6]: 0
[18]: 1
1.3 Immutability
It can’t be stressed enough that tuples are immutable. To drive that point home:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-1257c0aa9edd> in <module>
----> 1 t[0]= 'change'
Because of this immutability, tuples can’t grow. Once a tuple is made we can not add to it.
[20]: t.append('nope')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-20-b75f5b09ac19> in <module>
----> 1 t.append('nope')
2
1.4 When to use Tuples
You may be wondering, “Why bother using tuples when they have fewer available methods?” To
be honest, tuples are not used as often as lists in programming, but are used when immutability is
necessary. If in your program you are passing around an object and need to make sure it does not
get changed, then a tuple becomes your solution. It provides a convenient source of data integrity.
You should now be able to create and use tuples in your programming as well as have an under-
standing of their immutability.
Up next Files!