Topic Overview and Actualization

Hello, welcome back! In today's session, we'll delve deeply into Python tuples. These are collections of ordered items, which allow us to group related variables together. A key attribute of tuples is their immutability: once a tuple is initialized, it remains constant, ensuring the preservation of the grouped items. Let's dive into Python tuples!

Introduction to Python Tuples

Tuples are collections that permit duplicate items, and their elements can be of any type. Importantly, they are both "ordered" and "immutable". Tuple values are enclosed within parentheses (), separated by commas.

Suppose we have a student, and we'd like to store their grade in a single variable for compact and clear code. Here's how we can do that:

grade_mary = ("Mary", 95) # a tuple of two elements

If we need to store grades for multiple students, we can organize this into a list of tuples or a nested tuple:

grades = [("Mary", 95), ("John", 80), ("Susan", 75), ("Steve", 85)] # list of tuples
grades_tuple = ( ("Mary", 95), ("John", 80), ("Susan", 75), ("Steve", 85) ) # nested tuple

print(grades)       # Prints [('Mary', 95), ('John', 80), ('Susan', 75), ('Steve', 85)]
print(grades_tuple) # Prints (('Mary', 95), ('John', 80), ('Susan', 75), ('Steve', 85))
Creation of Python Tuples

Initializing tuples is a breeze; you just need to list comma-separated values within parentheses. You might be surprised to learn that even parentheses are optional! Python will still interpret the layer of grouped items as a tuple.

numbers = (1, 2, 3, 4)  # tuple of numbers
pickles = ("gherkins", "dill", "bread and butter")  # tuple of strings
tuple_without_parentheses = 'apple', 'banana', 'cherry'  # A tuple without parentheses
print(tuple_without_parentheses) # Prints ('apple', 'banana', 'cherry')
Accessing Elements in Tuples

Just as with a list, you can access elements in a tuple by using indexing. Additionally, we can access the elements from the end of the tuple by using negative indexing.

pickles = ("gherkins", "dill", "bread and butter")
print(pickles[0])  # Outputs: "gherkins"
print(pickles[-1])  # Outputs: "bread and butter"
print(pickles[0:2])  # Outputs: ("gherkins", "dill")
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal