Welcome to our Python Tuples tutorial! In this lesson, we'll delve into the world of tuples, a powerful and versatile data structure in Python. Let's get started! š
A tuple is a collection of ordered, immutable (cannot be changed once created) elements. Think of a tuple as a container that holds multiple values, just like a box holds multiple items.
# Creating a tuple
my_tuple = (1, "Hello", 3.14)š” Pro Tip: Tuples are denoted by parentheses () or a comma-separated list of elements enclosed within parentheses.
Tuples provide several benefits:
Python doesn't have specific types for tuples. However, tuples can contain different types of elements, such as integers, strings, floats, booleans, and even other tuples or lists.
# Mixed tuple
mixed_tuple = (1, "World", True, (1, 2, 3))To access elements in a tuple, use index numbers just like with lists. Remember, Python uses 0-based indexing, so the first element's index is 0.
# Accessing elements in a tuple
my_tuple = (1, "Hello", 3.14)
print(my_tuple[0]) # Output: 1
print(my_tuple[1]) # Output: Hello
print(my_tuple[2]) # Output: 3.14The length (or size) of a tuple is the number of elements it contains. In Python, you can find the length of a tuple using the built-in len() function.
# Finding the length of a tuple
my_tuple = (1, "Hello", 3.14)
print(len(my_tuple)) # Output: 3Although tuples are immutable, you can create a new tuple with the modified values. This is because the original tuple remains unchanged.
# Modifying a tuple (creating a new tuple)
my_tuple = (1, "Hello", 3.14)
new_tuple = (my_tuple[0], "World", my_tuple[2])
print(new_tuple) # Output: (1, 'World', 3.14)Both tuples and lists are sequences in Python, but there are some key differences:
What is a tuple in Python?
How can you create a tuple in Python?