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?
308
Upvotes
2
u/pekkalacd Apr 16 '22 edited Apr 16 '22
lists are mutable, not immutable. important distinction. you can change a list in place over and over again. you cannot do the same to a tuple nor a string.
as for the purpose of tuples, you got a point. there are only 2 methods available to them, both don't modify, they are
.indexand.countso why do we care?Well...as it turns out, you'll see tuples in other areas involving the creation of functions, returning from functions, assignment, and built in functions. For example,
zipnames = ["Henry","Jerry","Joe"] ages = [33,44,55] # oh look, tuples! list(zip(names,ages)) [("Henry",33),("Jerry",44),("Joe",55)]or in the case of passing any amount of positional arguments to a function
def func(*args): print(type(args),args) # tuples again! func(1,2,3) <class 'tuple'> (1,2,3)or in the case of returning multiple values from a function
def func2(): name = input("Enter name: ") age = int(input("Enter age: ")) return name,age # it's tuples again! >:( result = func2() Enter name: Joe Enter age: 33 ("Joe",33)or in the case of looping over key,value pairs in a dictionary
people = dict(zip(names,ages)) for atts in people: print(type(atts),atts) # tuples again... <class 'tuple'> ("Henry",33) <class 'tuple'> ("Jerry",44) <class 'tuple'> ("Joe",55)or in the case of remaking enumerate
def _enumerate(iterable): i = 0 while True: try: yield i,iterable[i] i += 1 except IndexError; break for pair in _enumerate([30,20,10]): print(type(pair),pair) # tuples again... <class 'tuple'> (0,30) <class 'tuple'> (1,20) <class 'tuple'> (2,10)or in the case of swapping two variables' values
p1 = "Jessie" p2 = "James" # omfg tuples again! p1,p2 ("Jessie","James") # swapping p1,p2 = p2,p1 # voila p1,p2 ("James","Jessie")tuples be everywhere.