Freeze Your Data: Discover the Magic of Python Tuples

What is Tuple ?
A tuple is similar data type as of list in Python and also a data structure because it stores a collection of data. This is why it is considered a built-in data structure in Python. A tuple is defined using square brackets ( ), and the elements inside it are separated by commas ( , ). In a tuple, we can store elements of any data type.

Tuple are immutable in nature, which means when one’s it created, we can’t change or modify it’s element at any point of code.
What happens if we create and modify elements of a tuple?
generate error because we cant modify tuple elements so we don’t have attribute like append() in Tuple

Accessing the element and Slicing operation


How to convert List in tuple or tuple in list ?
To convert a tuple into a list, we use the list( ) function and pass the variable we want to convert into a list inside the parentheses. Similarly, we can convert any sequence data type into a tuple.
a = (1, 2, 3, 4)
b = [1, 2, 5, 7]
s = "aryan"
c = list(a)
d = tuple(b)
e = tuple(s)

Concatenation of Tuples


Built-in Functions
1. len( ) :
return length of the tuple.

2. max( ) :
return max element of tuple.

3. min( ) :
return min element of tuple.

4. index( ) :
return index of element specified under parenthesis. if specified element is not present return error.

5. sum( ) :
return addition of element of tuple.

6. sort( ) :
It returns a new sorted list containing the elements of the tuple.

How is the immutable property a strength of a tuple?
1. Data integrity
Because a tuple is immutable, its data can't be changed under any circumstances, so we can rely on that data. This property makes it very useful when we want to store data that should never change.
2. Performance
A tuple is very fast compared to a list because of its immutability. Since we don't change or modify its elements, there is no risk of buffer overflow, and Python doesn't need to manage it, making the operation more efficient.
3. Hashable
Because it is immutable, we can use it as a key in a dictionary.
Now you understand what a tuple is and how its immutability is a strength.
#chaicode



