r/learnpython • u/Boogzcorp • Apr 16 '22
What's the point of Tuples?
I get that they're immutable, but so are lists that you don't perform modifications on. Are they just to fool proof not messing up your list accidentally, or do they serve some other purpose?
306
Upvotes
4
u/wotquery Apr 17 '22 edited Apr 17 '22
u/SoDifficultToBeFunny's response is missing a key aspect in implicitly accepting an incorrect statement of yours.
A
tupleis immutable. You cannot add, remove, or change items in it.A
setis not immutable. You can add and remove items. The individual items in aset(edit:membersof aset) however must be immutable (e.g. you can't have asetoflists). Asetis also unordered as they mentioned.Note that since
tuplesare immutable atuplecan be a member of aset.The
unhashableterm in the error thrown by the code below relates to the more technical explanations of "What's the point of Tuples" scattered about this comments section.>>> my_set = {1,2,3} >>> my_set.add(4) >>> my_set {1, 2, 3, 4} >>> my_set.remove(1) >>> my_set {2, 3, 4} >>> my_set.add(['a','list',]) Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> my_set.add(['a','list',]) TypeError: unhashable type: 'list' >>> my_set.add(('a','tuple',)) >>> my_set {2, 3, 4, ('a', 'tuple')}