Python tuples are a data structure that is an unchangeable, ordered sequence of elements. Since these elements are unchangeable, their values cannot be modified. Using tuples in Python are great for grouping data and each tuple element is called an item.
Python Internal Tuple Methods
Python Tuple Creation
Creating a list in Python is easy by using parenthesis () and surrounding the values with quotes if needed.
Input:
1 2 3 | groceries = ("milk", "eggs", "apples", "bread") print(f"Here's my grocery list: {groceries}") |
Output:
1 | Here's my grocery list: ('milk', 'eggs', 'apples', 'bread') |
Python Tuple Access
In order to access the items within a tuple, the index number will be executed to refer to the tuple item.
Input:
1 | print(f"My favorite grocery item is: {groceries[2]} ") |
Output:
1 | My favorite grocery item is: apples |
Python Tuple Looping
Within a tuple, a loop can print out each item that is in the list using a for loop.
Input:
1 2 | for x in groceries: print(f"Grocery item: {x} ") |
Output:
1 2 3 4 | Grocery item: milk Grocery item: eggs Grocery item: apples Grocery item: bread |
Python Tuple Validating Item
Python tuple item validating will determine if an item is in the tuple by using the keyword, in.
if…else Example 1
Input:
1 2 3 4 | if "oranges" in groceries: print("Yes, oranges are in the tuple.") else: print("No, oranges are not in the tuple.") |
Output:
1 | No, oranges are not in the tuple. |
if…else Example 2
Input:
1 2 3 4 | if "apples" in groceries: print("Yes, apples are in the tuple.") else: print("No, apples are not in the tuple.") |
Output:
1 | Yes, apples are in the tuple. |
Python Tuple Length
The internal method, len() will determine the length(item count) of a tuple.
Input:
1 | print(f"The length of the groceries tuple is: {len(groceries)} ") |
Output:
1 | The length of the groceries tuple is: 4 |
Python tuple() Constructor
The tuple() constructor method to create a new tuple.
Input:
1 2 3 | new_groceries_tuple = tuple(("milk", "eggs", "water", "chicken", "asparagus", "juice", "chips", "cookies")) print(f"New groceries tuple using the tuple() constructor method: {new_groceries_tuple} ") |
Output:
1 | New groceries tuple using the tuple() constructor method: ('milk', 'eggs', 'water', 'chicken', 'asparagus', 'juice', 'chips', 'cookies') |