<p>I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?</p>

[{'answer_id': 42048, 'author': 'Chris Upchurch', 'author_id': 2600, 'author_profile': 'https://Stackoverflow.com/users/2600', 'pm_score': 7, 'selected': True, 'text': "<ul>\n<li>Tuples are used whenever you want to return multiple results from a function.</li>\n<li>Since they're immutable, they can be used as keys for a dictionary (lists can't).</li>\n</ul>\n"}, {'answer_id': 42049, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 2, 'selected': False, 'text': '<p>I find them useful when you always deal with two or more objects as a set.</p>\n'}, {'answer_id': 42050, 'author': 'Magnus Hoff', 'author_id': 2971, 'author_profile': 'https://Stackoverflow.com/users/2971', 'pm_score': 1, 'selected': False, 'text': '<p>A list can always replace a tuple, with respect to functionality (except, apparently, as keys in a dict). However, a tuple can make things go faster. The same is true for, for example, immutable strings in Java -- when will you ever need to be unable to alter your strings? Never!</p>\n\n<p>I just read a decent discussion on limiting what you can do in order to make better programs; <a href="http://weblog.raganwald.com/2007/03/why-why-functional-programming-matters.html" rel="nofollow noreferrer">Why Why Functional Programming Matters Matters</a></p>\n'}, {'answer_id': 42052, 'author': 'sphereinabox', 'author_id': 2775, 'author_profile': 'https://Stackoverflow.com/users/2775', 'pm_score': 4, 'selected': False, 'text': '<p>Tuples make good dictionary keys when you need to combine more than one piece of data into your key and don\'t feel like making a class for it.</p>\n\n<pre><code>a = {}\na[(1,2,"bob")] = "hello!"\na[("Hello","en-US")] = "Hi There!"\n</code></pre>\n\n<p>I\'ve used this feature primarily to create a dictionary with keys that are coordinates of the vertices of a mesh.  However, in my particular case, the exact comparison of the floats involved worked fine which might not always be true for your purposes [in which case I\'d probably convert your incoming floats to some kind of fixed-point integer]</p>\n'}, {'answer_id': 42055, 'author': 'Andrew Grant', 'author_id': 1043, 'author_profile': 'https://Stackoverflow.com/users/1043', 'pm_score': 1, 'selected': False, 'text': '<p>A tuple is useful for storing multiple values.. As you note a tuple is just like a list that is immutable - e.g. once created you cannot add/remove/swap elements.</p>\n\n<p>One benefit of being immutable is that because the tuple is fixed size it allows the run-time to perform certain optimizations. This is particularly beneficial when a tupple is used in the context of a return value or a parameter to a function.</p>\n'}, {'answer_id': 42060, 'author': 'Martin Salias', 'author_id': 4020, 'author_profile': 'https://Stackoverflow.com/users/4020', 'pm_score': 2, 'selected': False, 'text': '<p>Tuples and lists have the same uses in general. Immutable data types in general have many benefits, mostly about concurrency issues.</p>\n\n<p>So, when you have lists that are not volatile in nature and you need to guarantee that no consumer is altering it, you may use a tuple.</p>\n\n<p>Typical examples are fixed data in an application like company divisions, categories, etc.  If this data change, typically a single producer rebuilts the tuple.</p>\n'}, {'answer_id': 48414, 'author': 'sherbang', 'author_id': 5026, 'author_profile': 'https://Stackoverflow.com/users/5026', 'pm_score': 3, 'selected': False, 'text': '<p>I like <a href="http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/" rel="noreferrer">this explanation</a>.</p>\n\n<p>Basically, you should use tuples when there\'s a constant structure (the 1st position always holds one type of value and the second another, and so forth), and lists should be used for lists of homogeneous values.</p>\n\n<p>Of course there\'s always exceptions, but this is a good general guideline.</p>\n'}, {'answer_id': 51200, 'author': 'Nick', 'author_id': 5222, 'author_profile': 'https://Stackoverflow.com/users/5222', 'pm_score': 0, 'selected': False, 'text': "<p>In addition to the places where they're syntactically required like the string % operation and for multiple return values, I use tuples as a form of lightweight classes.  For example, suppose you have an object that passes out an opaque cookie to a caller from one method which is then passed into another method.  A tuple is a good way to pack multiple values into that cookie without having to define a separate class to contain them.</p>\n\n<p>I try to be judicious about this particular use, though.  If the cookies are used liberally throughout the code, it's better to create a class because it helps document their use. If they are only used in one place (e.g. one pair of methods) then I might use a tuple. In any case, because it's Python you can start with a tuple and then change it to an instance of a custom class without having to change any code in the caller.</p>\n"}, {'answer_id': 39638334, 'author': 'Mayank Shekhar', 'author_id': 6505489, 'author_profile': 'https://Stackoverflow.com/users/6505489', 'pm_score': 2, 'selected': False, 'text': "<p>A tuple is a sequence of values. The values can be any type, and they are indexed by integer, so tuples are not like lists. The most important difference is that <strong>tuples are immutable.</strong></p>\n\n<p>A tuple is a comma-separated list of values:</p>\n\n<pre><code>t = 'p', 'q', 'r', 's', 't'\n</code></pre>\n\n<p>it is good practice to enclose tuples in parentheses:</p>\n\n<pre><code>t = ('p', 'q', 'r', 's', 't') \n</code></pre>\n"}, {'answer_id': 52500970, 'author': 'Lassi', 'author_id': 6272277, 'author_profile': 'https://Stackoverflow.com/users/6272277', 'pm_score': 3, 'selected': False, 'text': '<p><strong>The best way to think about it is:</strong></p>\n\n<ul>\n<li><strong>A tuple is a <a href="https://en.wikipedia.org/wiki/Record_(computer_science)" rel="noreferrer">record</a> whose fields don\'t have names.</strong></li>\n<li>You use a tuple instead of a record when you can\'t be bothered to specify the field names.</li>\n</ul>\n\n<p>So instead of writing things like:</p>\n\n<pre><code>person = {"name": "Sam", "age": 42}\nname, age = person["name"], person["age"]\n</code></pre>\n\n<p>Or the even more verbose:</p>\n\n<pre><code>class Person:\n    def __init__(self, name, age):\n        self.name = name\n        self.age = age\n\nperson = Person("Sam", 42)\nname, age = person.name, person.age\n</code></pre>\n\n<p>You can just write:</p>\n\n<pre><code>person = ("Sam", 42)\nname, age = person\n</code></pre>\n\n<p>This is useful when you want to pass around a record that has only a couple of fields, or a record that is only used in a few places. In that case specifying a whole new record type with field names (in Python, you\'d use an object or a dictionary, as above) could be too verbose.</p>\n\n<p><strong>Tuples originate from the world of functional programming</strong> (Haskell, OCaml, Elm, F#, etc.), where they are commonly used for this purpose. Unlike Python, most functional programming languages are statically typed (a variable can only hold one type of value, and that type is determined at compile time). Static typing makes the role of tuples more obvious. For example, in the Elm language:</p>\n\n<pre><code>type alias Person = (String, Int)\n\nperson : Person\nperson = ("Sam", 42)\n</code></pre>\n\n<p>This highlights the fact that a particular type of tuple is always supposed to have a fixed number of fields in a fixed order, and each of those fields is always supposed to be of the same type. In this example, a person is always a tuple of two fields, one is a string and the other is an integer.</p>\n\n<p><strong>The above is in stark contrast to lists</strong>, which are supposed to be variable length (the number of items is normally different in each list, and you write functions to add and remove items) and each item in the list is normally of the same type. For example, you\'d have one list of people and another list of addresses - you would not mix people and addresses in the same list. Whereas mixing different types of data inside the same tuple is the whole point of tuples. Fields in a tuple are usually of different types (but not always - e.g. you could have a <code>(Float, Float, Float)</code> tuple to represent x,y,z coordinates).</p>\n\n<p><strong>Tuples and lists are often nested.</strong> It\'s common to have a list of tuples. You could have a list of Person tuples just as well as a list of Person objects. You can also have a tuple field whose value is a list. For example, if you have an address book where one person can have multiple addresses, you could have a tuple of type <code>(Person, [String])</code>. The <code>[String]</code> type is commonly used in functional programming languages to denote a list of strings. In Python, you wouldn\'t write down the type, but you could use tuples like that in exactly the same manner, putting a <code>Person</code> object in the first field of a tuple and a list of strings in its second field.</p>\n\n<p><strong>In Python, confusion arises</strong> because the language does not <em>enforce</em> any of these practices that are enforced by the compiler in statically typed functional languages. In those languages, you cannot mix different kinds of tuples. For example, you cannot return a <code>(String, String)</code> tuple from a function whose type says that it returns a <code>(String, Integer)</code> tuple. You also cannot return a list when the type says you plan to return a tuple, and vice versa. Lists are used strictly for growing collections of items, and tuples strictly for fixed-size records. Python doesn\'t stop you from breaking any of these rules if you want to.</p>\n\n<p>In Python, a list is sometimes converted into a tuple for use as a dictionary key, because Python dictionary keys need to be immutable (i.e. constant) values, whereas Python lists are mutable (you can add and remove items at any time). This is a workaround for a particular limitation in Python, not a property of tuples as a computer science concept.</p>\n\n<p>So in Python, lists are mutable and tuples are immutable. But this is just a design choice, not an intrinsic property of lists and tuples in computer science. You could just as well have immutable lists and mutable tuples.</p>\n\n<p>In Python (using the default CPython implementation), tuples are also faster than objects or dictionaries for most purposes, so they are occasionally used for that reason, even when naming the fields using an object or dictionary would be clearer.</p>\n\n<p>Finally, to make it even more obvious that tuples are intended to be another kind of record (not another kind of list), Python also has <strong>named tuples</strong>:</p>\n\n<pre><code>from collections import namedtuple\n\nPerson = namedtuple("Person", "name age")\n\nperson = Person("Sam", 42)\nname, age = person.name, person.age\n</code></pre>\n\n<p>This is often the best choice - shorter than defining a new class, but the meaning of the fields is more obvious than when using normal tuples whose fields don\'t have names.</p>\n\n<p><strong>Immutable lists are highly useful for many purposes</strong>, but the topic is far too complex to answer here. The main point is that things that cannot change are easier to reason about than things that can change. Most software bugs come from things changing in unexpected ways, so restricting the ways in which they can change is a good way to eliminate bugs. If you are interested, I recommend reading a tutorial for a functional programming language such as Elm, Haskell or Clojure (Elm is the friendliest). The designers of those languages considered immutability so useful that <em>all</em> lists are immutable there. (Instead of changing a list to add and or remove an item, you <a href="https://en.wikipedia.org/wiki/Persistent_data_structure" rel="noreferrer">make a new list with the item added or removed</a>. Immutability guarantees that the old copy of the list can never change, so the compiler and runtime can make the code perform well by re-using parts of the old list in the new one and garbage-collecting the left-over parts when they are longer needed.)</p>\n'}, {'answer_id': 63481233, 'author': 'Sanmitha Sadhishkumar', 'author_id': 13827419, 'author_profile': 'https://Stackoverflow.com/users/13827419', 'pm_score': 0, 'selected': False, 'text': '<p>Tuples are used in :</p>\n<ol>\n<li>places where you want your sequence of elements to be immutable</li>\n<li>in tuple assignments</li>\n</ol>\n<pre><code>a,b=1,2\n</code></pre>\n<ol start="3">\n<li>in variable length arguments</li>\n</ol>\n<pre><code>def add(*arg) #arg is a tuple\n    return sum(arg)\n</code></pre>\n'}, {'answer_id': 72592849, 'author': 'hassanzadeh.sd', 'author_id': 9533909, 'author_profile': 'https://Stackoverflow.com/users/9533909', 'pm_score': 1, 'selected': False, 'text': '<p><strong>Use Tuple</strong></p>\n<ol>\n<li><p>If your data should or does not need to be changed.</p>\n</li>\n<li><p>Tuples are faster than lists. We should use a Tuple instead of a List if we are defining a constant set of values and all we are ever going to do\nwith it is iterate through it.</p>\n</li>\n<li><p>If we need an array of elements to be\nused as dictionary keys, we can use Tuples. As Lists are mutable,\nthey can never be used as dictionary keys.</p>\n</li>\n</ol>\n<p>Furthermore, Tuples are immutable, whereas Lists are mutable. By the same token, Tuples are fixed size in nature, whereas Lists are dynamic.</p>\n<pre><code>a_tuple = tuple(range(1000))\na_list = list(range(1000))\na_tuple.__sizeof__()  # 8024 bytes\na_list.__sizeof__()   # 9088 bytes\n</code></pre>\n<p>more information :\n<a href="https://jerrynsh.com/tuples-vs-lists-vs-sets-in-python/" rel="nofollow noreferrer">https://jerrynsh.com/tuples-vs-lists-vs-sets-in-python/</a></p>\n'}]
['https://Stackoverflow.com/questions/42034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/577/']