#Python Tuples
Tuples are used to store multiple items in a single variable. It is one of four built-in data types in Python used to store collections of data; the others are List, Set, and Dictionary, each with distinct qualities and use cases.
A tuple is a collection that is ordered and unchangeable.
#Key Characteristics
- Ordered: Items have a defined order that will not change.
- Unchangeable: You cannot change, add, or remove items after the tuple has been created.
- Allow Duplicates: Since tuples are indexed, they can contain multiple items with the same value.
#Basic Syntax
Tuples are written with round brackets ().
pythonthistuple = ("apple", "banana", "cherry")
print(thistuple)
#Indexed Access
Tuple items are indexed. The first item has index [0], the second has index [1], and so on.
#Tuple Length
To determine how many items a tuple has, use the len() function:
pythonthistuple = ("apple", "banana", "cherry")
print(len(thistuple)) # Output: 3
#Creating a Single Item Tuple
To create a tuple with only one item, you must add a trailing comma. Otherwise, Python will identify the variable as a string (or whatever the item type is).
python# Correct way to create a one-item tuple
thistuple = ("apple",)
print(type(thistuple)) # <class 'tuple'>
# NOT a tuple
thistuple = ("apple")
print(type(thistuple)) # <class 'str'>
#Data Diversity
Tuple items can be of any data type and can even contain a mix of different types.
python# Tuples with uniform data types
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
# Tuple with mixed data types
mixed_tuple = ("abc", 34, True, 40, "male")
#The type() Function
From Python's perspective, tuples are objects with the data type tuple.
pythonmytuple = ("apple", "banana", "cherry")
print(type(mytuple)) # <class 'tuple'>
#The tuple() Constructor
You can also use the tuple() constructor to create a tuple. Note the double round brackets.
pythonthistuple = tuple(("apple", "banana", "cherry"))
print(thistuple)
#Summary of Python Collections
Here is a quick breakdown of the four built-in collection data types in Python:
| Collection | Ordered | Changeable | Duplicates | Notes |
|---|---|---|---|---|
| List | Yes | Yes | Yes | Most flexible collection. |
| Tuple | Yes | No | Yes | Faster and safer for data that shouldn't change. |
| Set | No | No\* | No | Items are unindexed. No duplicate members. |
| Dictionary | Yes\\ | Yes | No | Key-value pairs. No duplicate keys. |
\Set items are unchangeable, but you can remove and add new items. \\*As of Python version 3.7, dictionaries are ordered. In 3.6 and earlier, they are unordered.