A Python tuple just like a list is a collection of items. Some key differences between a Python tuple and Python List are:
- Python tuple are created by adding comma separated values inside parentheses
- Python tuple are immutable wherein once values are added to tuple, they can’t be changed
Let’s dive in and learn more about how to use a Python tuple.
Creating a Python Tuple
Python tuple can be created by specifying comma separated values inside of parentheses
( ). Values inside of a tuple cannot be modified once created. Let’s create a tuple of the first 5 odd numbers and then try to change one of them to be a number that is not odd. As you can see below, changing values inside of a tuple throws an error as tuples are immutable.
Python tuples follow the idea of packing and unpacking values i.e. while creating a tuple parentheses
( ) are optional and just providing a comma-separated value will create a tuple as well (also known as packing). Similarly, when trying to access each value in the tuple, the values can be assigned to individual variables (also called unpacking).
Let’s create a tuple called
student with name, age, course, phone number using PACKING and then UNPACK those values from the student tuple into individual variables.
Creating a Python Tuple With Zero or One Item
Creating a python tuple with either zero or one element is a bit tricky. Let’s take a look.
- Python tuple with zero item can be created by using empty parentheses
- Python tuple with exactly one item can be created by ending the tuple item with a comma
Accessing Items From the Tuple
Items from the tuple can be accessed just like a list using
- Indexing - returns the item
- Negative Indexing - returns the item
- Slicing - returns a tuple with the items in it
Let’s access course from student tuple using above mentioned techniques
Kick-Start Your Data Career
We offer a wide variety of programs and courses built on adaptive curriculum and led by leading industry experts.
- Work on projects in a collaborative setting
- Take advantage of our flexible plans and scholarships
- Get access to VIP events and workshops
The Python certificate course provides individuals with fundamental Python programming skills to effectively work with data.
Taught by data professionals working in the industry, the part-time Data Science course is built on a project-based learning model, which allows students to use data analysis, modeling, Python programming, and more to solve real analytical problems.
The Data Science bootcamp is an intensive course designed to launch students' careers in data.
The part-time Data Analytics course was designed to introduce students to the fundamentals of data analysis.