In python, the list
data structure is a sequence of elements.
Similarly, a tuple
is also a sequence of elements, however, tuples are immutable
.
Whats the reason for making such a similar data structure, thats only feature, as opposed to lists, is that it can't be changed? Does it perhaps save memory space, by being immutable?
Also if a list and a tuple contains the exact same data, will they use the same amount of space in the memory?
The advantages of tuples over the lists are as follows: Tuples are faster than lists. Tuples make the code safe from any accidental modification. If a data is needed in a program which is not supposed to be changed, then it is better to put it in 'tuples' than in 'list'.
Tuples allow duplicate members and are indexed. Lists Lists hold a collection of objects that are ordered and mutable (changeable), they are indexed and allow duplicate members. Sets Sets are a collection that is unordered and unindexed. They are mutable (changeable) but do not allow duplicate values to be held.
Advantages of Tuples in Python over Lists Following are some of the main advantages: Iteration in a tuple is faster as compared to lists since tuples in Python are immutable. Tuples are generally used for different Python Data Types; whereas, lists are used for similar data types.
Immutable types are hashable, and can be used as dictionary keys. This works:
key = (1, 2, 3)
d = {key: 1}
But this doesn't:
key = [1, 2, 3]
d = {key: 1}
If it did, what would you expect this to do?
key[0] = 2
print d[key] # id(key) hasn't changed, so surely the lookup should still work
print d[[1, 2, 3]] # but also, we stored a piece of data at [1, 2, 3], didn't we?
print d[[2, 2, 3]] # but if d[key] works, surely we can expand key to its value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With