Tuple in Python

Tuple in Python

In Python, a tuple is a built-in data structure that is similar to a list, but with one major difference: tuples are immutable, meaning that once a tuple is created, its contents cannot be modified. This makes tuples useful for storing fixed collections of data.

Tuples are defined using parentheses (), with each element separated by a comma. For example, we can create a tuple of integers like this:

my_tuple = (1, 2, 3, 4, 5)

We can also create a tuple of strings:

my_tuple = ('apple', 'banana', 'cherry')

We can access individual elements of a tuple using their index, just like with lists. However, because tuples are immutable, we cannot modify their contents:

first_element = my_tuple[0]  # Access the first element
my_tuple[1] = 'orange'      # This will raise a TypeError!

We can add two tuples together using the + operator to create a new tuple:

my_tuple = (1, 2, 3) + (4, 5, 6)

We can also create a tuple with a single element by including a trailing comma after that element:

single_tuple = (1,)

Overall, tuples are useful when we want to store a fixed collection of data that will not be modified. They can also be used as dictionary keys or as elements in sets, because they are immutable.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

VLAN Trunking Protocol
VTP Modes

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?