r/learnpython • u/Pure-Homework681 • Mar 27 '23
Actually using a tuple
Can someone, please, give me a "real-world" example on the use of a tuple? I'm learning through w3schools. The idea of a tuple sort of makes sense, but I have no idea how it would/could be applied.
147
Upvotes
3
u/[deleted] Mar 27 '23
One use case for tuples is to have multiple assignments in one go.
For example swapping:
Another contrived example is to compute fibonacci sequence:
A more nuanced use-case is if you want to write multiple things to csv using writerow() method. It takes as input a tuple.
The gist of using a tuple over a list or other containers is to use it as a very short aggregate where using a class'd be an overkill. If you're familiar with C (or C++), think of tuple as POD :) Also tuples are immutable which makes them more memory efficient. The following contrived test shows that for cpython :)