Tuple is a linear data structure which more or less behaves like a python list but with a really important difference, that a tuple is immutable. Immutable means that this structure can't be changed after it has been created, it can't be mutated if I may.
Tuples being immutable are more memory efficient than list as they don't over allocate memory. Okay, so what this means is, when a list is created it takes up and reserves extra spaces of memory than needed for the original elements as new elements might be added to the list later and allocating memory on every addition would be quite inneficient but tuples, once created surelly won't change the numbers of elements in it later on, so it allocates exactly how much memory is needed.
Almost all the list operations work for tuples except the ones which mutate it, for example, insert, append, remove etc.
Declaring a tuple :
Tuples can be initialise in a manner similar to list,
But there's an important catch to it, if you declare a tuple that has a single element like this,
t = (1)
,then Python is going to recogonise it as a single element and not a tuple.To declare a tuple with single element, a " , "(comma) needs to be added before putting the closing bracket. As it is also said in the Python docs, its the commas that make the tuple, not the brackets.
t = (1,)
Now it will recogonise this as a singleton tuple(tuple containing one element).
Important tuple methods -
1) "
in
" operatorThis is used to check wether something exists in a tuple or not and returns a boolean value.
2)
len()
Return the length of the tuple
3)
min()
and max()
These both functions respectivelly return the minimum or the maximum value in a tuple
4)
count()
Returns the number of times an element appears in the tuple
5)
sorted()
Tuples can also be sorted but as they are immutable, it does not happen in place, that means the sorted method creates and returns a new list which is the sorted version of the original one.
Great Post!
ReplyDeleteIt is quite comprehensive and very easy to understand!
Happy you liked it!
Delete