Tuples are a fundamental data structure in Python that allow for the creation of immutable groups of objects. Once a tuple is created, its values cannot be modified, added, or removed. Tuples are created using parentheses instead of square brackets, similar to lists:
names = ("Roger", "Syd")
Just like lists, tuples are ordered, which means you can access their values using index values:
names[0] # "Roger"
names[1] # "Syd"
You can also use the index()
method to find the position of a value within a tuple:
names.index('Roger') # 0
names.index('Syd') # 1
Negative indexing can also be used to search from the end of the tuple:
names[-1] # "Syd"
The len()
function can be used to count the number of items in a tuple:
len(names) # 2
To check if an item is contained within a tuple, you can use the in
operator:
print("Roger" in names) # True
Slicing can be used to extract a portion of a tuple:
names[0:2] # ('Roger', 'Syd')
names[1:] # ('Syd',)
The len()
function can also be used to get the number of items in a tuple, just like we did with strings:
len(names) # 2
To create a sorted version of a tuple, you can use the sorted()
function:
sorted(names)
New tuples can be created by concatenating existing tuples using the +
operator:
newTuple = names + ("Vanille", "Tina")