Python Tuple
smart and simple
So, talking about tuple in python is a collection of items inside the round brackets.
The basic difference between list and tuple is that tuple is immutable.
If you don’t know what is mutable and immutable, read my first article on the list in python.
whenever we return more than one value from a function python incorporates those values into a tuple data structure.
here values we are getting are in the tuple data structure.
What if I want a tuple with a single element, let’s check this out
Ok but let me check its type whether it is a tuple or not…
oops! I was expecting a tuple but it is an int, why it is so?
let’s understand it better
considering 30 as a tuple will cause an error to the program that’s why any single value inside round brackets will be treated as an integer.
then how to create a tuple of a single value? for that, we have to separate that value with a comma(,) which is a separator for an object.
now you can see it is a tuple.
As tuple is immutable which means we cannot add or remove value from the tuple.
we do have two functions that are count and index in the tuple.
The count function will count the occurrences of an element and the index function will return the index of an element.
Can we have a list inside a tuple ?
yes, it is possible.
As we discussed that tuple is immutable means we cannot insert or delete an element from the tuple.
let me check.
here you can see value is added but how?
let me ask you are we changing any id of A or deleting id of A?
of course not, we adding new id in A[2] which is perfectly valid because A[2] is a list and we know that list is a mutable object. That’s we don’t get any error.
This is how tuple works ….
Thanks for reading !!