Python Tuples: An Introduction
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:
1 | names = ("Roger", "Syd") |
Just like lists, tuples are ordered, which means you can access their values using index values:
1 | names[0] # "Roger" |
You can also use the index()
method to find the position of a value within a tuple:
1 | names.index('Roger') # 0 |
Negative indexing can also be used to search from the end of the tuple:
1 | names[-1] # "Syd" |
The len()
function can be used to count the number of items in a tuple:
1 | len(names) # 2 |
To check if an item is contained within a tuple, you can use the in
operator:
1 | print("Roger" in names) # True |
Slicing can be used to extract a portion of a tuple:
1 | names[0:2] # ('Roger', 'Syd') |
The len()
function can also be used to get the number of items in a tuple, just like we did with strings:
1 | len(names) # 2 |
To create a sorted version of a tuple, you can use the sorted()
function:
1 | sorted(names) |
New tuples can be created by concatenating existing tuples using the +
operator:
1 | newTuple = names + ("Vanille", "Tina") |
tags: [“Python”, “tuples”, “data structure”, “immutable”, “indexing”, “slicing”]