Create and Access Tuples
In this step, you will learn how to create tuples and access their elements. Tuples are ordered, immutable collections of items, meaning their contents cannot be changed after creation.
First, locate the file explorer on the left side of the WebIDE. Find and open the file named tuple_basics.py. We will write our code in this file.
Let's start by creating a few different types of tuples. Add the following code to tuple_basics.py:
## Create an empty tuple
empty_tuple = ()
print("Empty tuple:", empty_tuple)
print("Type of empty_tuple:", type(empty_tuple))
## Create a tuple with a single element (note the trailing comma)
single_element_tuple = (50,)
print("\nSingle element tuple:", single_element_tuple)
print("Type of single_element_tuple:", type(single_element_tuple))
## Create a tuple with multiple elements
fruits = ("apple", "banana", "cherry")
print("\nFruits tuple:", fruits)
## Create a tuple from a list using the tuple() constructor
numbers_list = [1, 2, 3, 4]
numbers_tuple = tuple(numbers_list)
print("\nTuple from list:", numbers_tuple)
After adding the code, save the file (you can use the Ctrl+S shortcut). Then, open the terminal at the bottom of the WebIDE and run the script with the following command:
python tuple_basics.py
You should see the following output, which confirms the creation and types of your tuples:
Empty tuple: ()
Type of empty_tuple: <class 'tuple'>
Single element tuple: (50,)
Type of single_element_tuple: <class 'tuple'>
Fruits tuple: ('apple', 'banana', 'cherry')
Tuple from list: (1, 2, 3, 4)
Now, let's learn how to access the elements within a tuple. You can use indexing (starting from 0) to get a single element and slicing to get a sub-sequence of elements.
Add the following code to the end of your tuple_basics.py file:
## Define a sample tuple for accessing elements
my_tuple = ('p', 'y', 't', 'h', 'o', 'n')
print("\nOriginal tuple:", my_tuple)
## Access elements using indexing
print("First element (index 0):", my_tuple[0])
print("Last element (index -1):", my_tuple[-1])
## Access elements using slicing
print("Elements from index 1 to 3:", my_tuple[1:4])
print("Elements from index 2 to the end:", my_tuple[2:])
print("Reverse the tuple:", my_tuple[::-1])
Save the file again and run the script from the terminal:
python tuple_basics.py
The complete output will now include the results of accessing the tuple elements:
Empty tuple: ()
Type of empty_tuple: <class 'tuple'>
Single element tuple: (50,)
Type of single_element_tuple: <class 'tuple'>
Fruits tuple: ('apple', 'banana', 'cherry')
Tuple from list: (1, 2, 3, 4)
Original tuple: ('p', 'y', 't', 'h', 'o', 'n')
First element (index 0): p
Last element (index -1): n
Elements from index 1 to 3: ('y', 't', 'h')
Elements from index 2 to the end: ('t', 'h', 'o', 'n')
Reverse the tuple: ('n', 'o', 'h', 't', 'y', 'p')
You have now successfully created tuples and accessed their elements.