Whatâs a Tuple?
- A tuple is a type of sequence that resembles a list, except that, unlike a list, a tuple is immutable (itâs structure canât change).
How Can I Define a Tuple?
- A tuple looks just like a list except you use parentheses instead of square brackets.
- Once defined, you can access individual elements by using each itemâs index, just as you would for a list.
- Example: If we have two colors that should always remain the same, we can ensure that the colors donât change by putting the colors into a tuple:
python
1colors = ('purple','gold')
2
3print(colors[0])
4print(colors[1])Output:
1purple
2gold- Note what happens if we try to change one item in the list:
python
1colors = ('purple','gold')
2
3colors[0] = "violet"
4
5print(colors[0])
6print(colors[1])Output:
1colors[0] = "violet"
2TypeError: 'tuple' object does not support item assignmentTuples are Practical!
- They are used to group together related data, such as a personâs name, their birthdate and their gender.
- Tuple arrays can themselves be other tuples. For example, we could improve the information about a certain object, such as a student, to hold not only his/her name but other attributes as well.
- Example:
python
1nationalParks = (("Great Smoky Mountains", "NC"),
2 ("Arches", "UT"),
3 ("Yosemite","CA"))
4
5print(nationalParks[1])Output:
1('Arches', 'UT')