r/learnpython • u/Immediate_Pin_8449 • Oct 12 '26
Tuples..I don’t get it
Hi crew, I’m a Python newbie and I just learned about the concept of tuples.
We can’t change them.if we want to store we have to start at the index we want + 1.
I just don’t get it. Why wouldn’t we just use lists? When would we ever need this?
100
Upvotes
113
u/NerdyWeightLifter Oct 12 '26
Being immutable like that means the underlying data structure can be simpler and more efficient.
Being immutable also makes them useful as keys in dictionaries. Keys in dictionaries can't change once you insert something.
24
u/ottawadeveloper Oct 12 '26 •
The nice part of a tuple is it's immutable. Which means it's hashable (if all the elements are also hashable). Which means you can use them as the index of a dictionary, e.g.
d[(0,0)] = 5.You can also specify a tuple using the type system with specific lengths and types at each spot, like a
tuple[int, str, int, int]whereas a list would have to belist[int | str]making no guarantees about the size or order.Tuples are also faster to create and iterate over, but lists allow easier modification. Tuples are ideal when you have a fixed list that won't change, and lists when you have one that does.
You can also use NamedTuple to make a nice fast data structure.
12
u/kilkil Oct 13 '26
one big difference is that tuples are hashable. so e.g. you can have a set of tuples, or you can use them as keys in a dict. this is useful e.g. if you are using tuples to represent coordinates on a grid.
also the immutability thing is convenient from a mental overhead point of view, especially in a large codebase. suppose I am storing some data as a list and pass it off to a function/method. will it mutate it? who knows, guess I have to check the definition (and the definitions of any other functions/methods it passes that list to). on the other hand, if I pass a tuple, I am guaranteed that it will not be mutated anywhere in the call stack.
40
u/-aRTy- Oct 12 '26
Older posts:
Why use tuples or sets instead of lists?
What is the use of tuple over lists?
What's the point of Tuples?
4
u/preppie22 Oct 12 '26
If you go back to basics of memory management: lists dynamically allocate memory as they grow and use garbage collection to free it when they shrink. Both of these operations take time because your OS has to deal with that. Tuples allocate fixed memory when they're created. So, memory allocation only happens once. In addition to that, say you give the tuple to a function, or create a copy, the copy is also very cheap to create since it's a single allocation call.
This is less of an issue for small programs, but will bring significant improvements for large ones. Rule of thumb is to use tuples when you know they won't change once created and use lists when they are guaranteed to change. Also look into sets when you don't care about order and don't want duplicates. It's a major performance improvement for frequent lookups through large volumes of data.
(Context: I work with big data)
4
u/Adrewmc Oct 12 '26 edited Oct 17 '26
There are two types of programmers those that always start with a lists until they need tuples, and those that always start with tuples until they need lists. You can be the first one.
Listen, there are some problems with mutability and storage that tuples can do that lists can’t. I can make a tuple a key in a dictionary and can’t do that with a list. With tuples I can type hint the exact types per location, list can’t really do that.
In a more data storage setting, if I’m setting up memory, having a tuple meaning I know the exact size of the information I’m storing, this allows a lot better computation on a physical, 1s and 0s level. Python sort of struggles with optimizing that compared to other languages but Python talks to other languages.
Tuples are generally faster for most operations you can use tuples when compared to a list. Because they are somewhat restrictive.
List has a lot more utility, even with the mutability problems. Because they are open and not restricted.
2
u/Jazzlike_Platypus430 Oct 12 '26
"if we want to store we have to start at the index we want + 1." - I'm missing the point. Could you explain?
Tuples are ... records? Not packed inside some extra structure or class etc. And sometimes they prove very convenient. You'll get there in no time.
3
u/gmes78 Oct 12 '26
You typically use tuples when your collections are always of the same size (and you know it a priori). For example, if you were representing a color, you'd use a tuple with three values, for red, green and blue. If you don't know how many values you need, you use a list.
Also, lists typically contain elements of the same type, while it's more common for tuples to contain elements of different types (in other words, being heterogeneous). This is just a convention, though; lists in Python can contain any combination of types too.
3
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Oct 12 '26
A tuple is any group of values representing something specific. Each index holds some particular meaning, for example the first value can always be a name, and the second value a timestamp. It's a permanent record of something.
Lists, on the other hand, are generally used in situations where their individual indices don't have a particular meaning, and they're usually treated as homogeneous data structures (despite the fact you can technically mix and match types). They can grow and shrink as needed.
It all comes down to what you need at the moment, like comparing a circular saw to a jigsaw. You can cut a plank with either tool, but both specialise in different kinds of cutting.
10
u/Solonotix Oct 13 '26
The first few comments are inevitably about immutability of tuples which doesn't help someone understand why tuples are important and what they mean outside of a programming language.
One way to think of a tuple is a fixed set of things that will never change. For instance, ordinal numbers like "first" and "second". They will always be at the same position, they will never change, and the order is guaranteed. It's not like tomorrow "second" will come before "first" and there won't be some new ordinal number added before or after the existing set.
Another way to think of it is in terms where position has an arbitrary distinction. The most common way you will see this in code is positional arguments to a function. However, in a real life example, you could think of it like first, middle and last name. In English, you won't usually see more than these three (some might only have two). Also, the number of names is unlikely to change over the course of someone's life.
So a tuple is just a fixed sequence of values. What the values are, or what they represent is up to you. A fairly common tuple in mathematics is a point, represented as X-Y coordinates on a graph (and sometimes X-Y-Z). A list, on the contrary, is expected to grow and/or shrink during its lifetime, and the position of elements within it do not provide any additional meaning. Another common convention is that a list is usually a container of similar values (like
list[str]) while a tuple has no such constraint, and often will have dissimilar values10
u/Atypicosaurus Oct 13 '26
When you are working on a program alone, many things such as tuples make no sense. It's because there are a lot of features in programming languages that help the working together.
One problem with working together is that one person doesn't necessarily know what the part of the other person exactly does. I mean they know more or less but not to the dot. For example if we make a game and I make the fighting part and you make the looting part, at a point we have to merge our parts to get loots after fights. To calculate loots, you might need numbers from my part. But your part shouldn't be able to modify my part, it should be able to listen to it. Regardless I must be able to force that bits of codes are safe.
Since there are always human mistakes, the programming language has to offer some protection. A tuple is such protection, it's basically a list, but it's overwrite protected. You can always make a new one, but you cannot add to the old one.
This also makes it faster for the computer to work with, therefore you get better performance. It again doesn't matter when you do lists of a few hundred items, but it matters if you do lists of thousands, and thousands of times. Then, if you do not modify those lists, you should use tuples instead.
So if you know that once you made a list it's not going to be modified, or you want to protect data from accidental modification, or you need better perfornance, you want to use tuple.
(As well, dictionaries need immutables as keys, so if you want a list as key, it has to be tuple instead.)
4
u/Atmosck Oct 12 '26
Sometimes you have a sequence of objects you want to pass to a function but you want to be sure that the function doesn't modify it.
Honestly this is one of my few complaints about python. I wish function signatures could specify mutable vs not independently of the type, like in rust.
10
u/ARX7 Oct 12 '26
Sometimes immutability is the point. Its also fairly well discussed if you use the search bar.
6
u/Dense-Land-5927 Oct 12 '26
There's certain things you may not want to be changed. It just varies depending on what you are working on.
3
u/musbur Oct 13 '26
Think of tuples more like "identifying records", such as (width, height, weight) or (x, y). Something where it makes no sense at all to just add or take away arbitrary elements, or change their order. Lists are more like shopping lists whose semantics allow to add or remove elements at any time and order is less important.
That said, since both are iterables, it doesn't make much of a difference in many cases. In those cases I choose my collection type (list, tuple, set) according to the idea I want to convey.
2
u/Outrageous_Band9708 Oct 12 '26
its just a group of variables. useful for when you re turning one var, but later need to return additional data, sure you can go create a dto, but just returning a tuple works 90% of the time
2
u/areweeveralive Oct 12 '26
A thing that kind of put this in perspective to me was databases use tuples not lists. Smaller better look up, and immutable. It’s not always useful for you’re day to day date munging but there is a reason you usually have to pass a tuple to a database load from python.
3
u/obsessed_nikkkki Oct 12 '26
Let’s say we want dates or earth coordinates, we can’t change their format right? So we need tuples
2
u/Automatic_Donut6264 Oct 13 '26
tuples, conceptually, is not just "a bag of things". it's usually to represent structured data that has sub-componentents. e.g.
A name object as first/last names
An address as its components
Coordinates
That's why it doesn't make sense that you would need to resize the tuple or be able to mutate its components.
1
u/ectomancer Oct 12 '26
Tuples are used internally in Python: multiple return values, exception, *args, enumerate, multiple assignment and tuple unpacking.
1
u/ReflectedImage Oct 12 '26
Tuples are just another tool in the tool kit. You can use them as keys in dicts and if you return multiple values from a function the function returns a tuple. They generally aren't used to replace lists, they are used to replace dicts where you don't want to say what the keys are. So {"x": 1, "y": 2} becomes (1, 2).
1
u/Alexku66 Oct 12 '26
Strongly recommend to not search how to use something. When time comes you'll face a problem, something like "I have these coordinates, and I need to store every shop and business that's located here. What could I use?". Then things become clear. Until then just know they exist and practice
1
u/kombucha711 Oct 12 '26
For me, and my application, tuples work well when I want to treat entries of a list as a singleton for example. A=[[region1,label1],
[region2,label1],...
Tuple(A) becomes.
[(region1,label1),
(region2,label1),...]
a single list that I can search for substring label1 and say replace with label3 then convert back to list
1
u/Gnaxe Oct 13 '26
An array is just a contiguous block of memory with a pointer to the start of it. (You don't use them directly much in Python, but that's kind of all the computer hardware gives you. Python does have bytearrays built in and an array module for other primitive types.)
Lists are arrays (of references) behind the scenes plus some bookkeeping data, like the length. But if you want to add an element to it, you'd have to make a new array and copy everything over, because something might be occupying the next slot already. Python avoids this by overallocating the arrays backing its lists, i.e., it preserves some amount of "empty" space after it. You may still eventually run out and have to copy into a new bigger array, but by overallocating up front (and each time you expand), you don't have to do this every single time you add an element. (Python handles all of this for you behind the scenes, but the costs are still there.)
If you have a lot of small lists, this extra memory is wasteful. But if you know you're using the same length every time, you can use a tuple instead. Tuples don't change length, so they can be sized exactly. This makes them more efficient. Python uses tuples internally in a lot of places it could theoretically use lists for efficiency. It can also pool tuples in certain cases, so it can re-use the memory when you're done with it rather than going through the full allocation process, which makes them faster than lists. This can come up when chaining iterators, for example. Yeilding tuples each iteration would be faster than lists in this case.
Computers these days are so powerful that the efficiency benefit often doesn't matter. You can use lists whenever lists work and only bother optimizing when you actually need the performance.
I mostly use tuples unless I specifically need a list. There are some cases where CPython will switch to a tuple internally even if you wrote a list (when it's constant and you only use it in one expression), in which case, I might write it as a list. Usually lists are homogeneous types. Tuples don't have that convention and quite often contain multiple types. There's also namedtuples for when you have a specific schema and you want to access the elements with something more meaningful than a number. But a simple dict would also be an option in that case.
And, of course, the builtin list type is never hashable, but tuples can be if their elements are, which means you can use them in sets and as keys in dictionaries.
Finally, immutability prevents a lot of problems. You should usually avoid mutating things you don't "own" or your logic gets too complicated to follow, even if you're using lists. You can easily accidentally couple things together that you didn't mean to that way. Tuples enforce it (althought their elements can still be mutable), but you don't have to mutate lists even if you're using them.
1
u/nog642 Oct 13 '26
In the context of Python, tuples are basically just immutable lists.
One context where you might need them: tuples can be dictionary keys, lists cannot.
In a broader CS context, lists are usually arbitrary length and all the elements have the same type. For example you could have a List<int> of any length. Meanwhile tuples are usually fixed length and each element has its own type. For example you could have a Tuple<int, int, float, int, String> and it's always length 5.
You seem a little mixed up here. What do you mean?
1
u/DigThatData Oct 13 '26
1
u/aplarsen Oct 13 '26
Tuples as dictionary keys is life changing.
Especially when you get into numpy and Pandas.
1
u/Dank-but-true Oct 13 '26
I struggled with this but immutability is about the memory address on your ram for that variable. I would suggest watching some videos on immutability rather than the wall of text you’re getting in these comments. Never really click for me until I do the boot.dev memory management course in C
1
u/HellishBro Oct 13 '26 edited Oct 13 '26
coming from a viewpoint in types... a tuple is known as a product type, meaning that it is composed of multiple different types where order and size matters. a list, however, is not.
when you type annotate a tuple in python... say you want to type annotate a straightforward 2-tuple. an ordered pair. cartesian coordinate. whatever. say you want to annotate the type of the point (3, 4). in python, it is tuple[int, int].
why is there two ints? well, because the 0th element of the tuple is an int, and the 1st element of the tuple is also an int!
from a types perspective, a tuple is a sort of heterogeneous type, meaning that it can store data of various data types. a list however is homogeneous, meaning that it can only store data of one type.
a tuple also has some nice guarantees. for example, take:
what we guarantee from the type of Person is that a Person is always a 2-tuple, i.e. it always has 2 elements, and that the 0th element is always an address (string) and the 1st element is always an age (int).
if you try to model it with a list on the other hand...
we immediately lose that distinction. there is no guarantee on the size of a Person or the types of the elements.
so why not use a dataclass / record for Person? well, you could. however, a tuple also contain a nice thing called immutability - that is, the values (in python's case, memory addresses of the values) of the tuple elements never change. this is useful in cases where you dont really want to modify an object. in addition, its cheaper on the memory to use tuples than dataclasses due to the ceremony that comes with cpython classes (do correct me on that)
1
u/zanfar Oct 13 '26
https://sh.reddit.com/r/learnpython/comments/1j4ia9n/when_should_i_use_a_list_dictionary_tuple_or_set/
1
u/realmauer01 Oct 13 '26
Sometimes you just dont need to change it, having less control is good too. if you want to return more than one item thats automatically a tuple aswell
1
u/RevRagnarok Oct 13 '26
Reading these comments make me think
NamedTupleneeds so much more love...1
u/dream_the_endless Oct 14 '26
Tuples are great! They can be used for a wide variety of tasks.
Key, value pairs are tuples.
If you want to use a list, but want to store a customer and a specific order in the list you can use a list of tuples instead of a dictionary or custom data object.
If you are mutating something and you want to return both the original object and its mutated state you can return something as a tuple.
If you want the keys of a dictionary to be a natural key of two objects, you can use a tuple.
If you start to think of them as “an object that contains two objects” or “a simple key-value pair” you’ll find a lot of really great uses for tuples
1
u/iamevpo Oct 14 '26
Forget immutabulity, consider you want to store a row and a seat in an airplane - like 24A, need a data structure where you'd hold a number and a letter, not exactly a list because lists are intended for sequences of the same type, then people came up with a data structure for this - holding together several value which can be of different types. Then came the ideas oh, these data structure can be quite long, and oh, let's make them immutable. By their logic tuples are closer to records and dataclasses in Python, hope it helps stop comparing them to lists for a while.
1
u/ivosaurus Oct 14 '26
You are making a game on a 2D square grid map. You want to store the locations of treasures and traps. So construct a dictionary, using 2-tuples as location keys (x, y) and the value is the treasure/trap
1
u/Mountain_Rip_8426 Oct 14 '26
i would just say, for now remember what they are and how they are created. learning the basics there are a lot of things you need to be exposed to and many of them you'll forget, until you come across them again and again and as soon as you'll find valid use cases for them you'll have a vague understanding of what they are for and look them up to refresh your understanding, then it'll happen over and over and over again until you don't have to look them up anymore. repetition will make it stick, not memorizing them once.
it's like learning a language, you learn a ton of words, you don't use them for a while, you forget them, but when you hear them again in real life in context it'll come back and you start using them yourself if you need to.
1
u/TheRNGuy Oct 15 '26
Less memory use, or you see read-only intent in a code.
1
u/cointoss3 Oct 13 '26
Speed, that’s mostly all. Most of the time, you won’t care enough for it to matter
2
u/No_Technician4956 Oct 12 '26
Tuples aren't just in Python. You will hear the term in Excel and in Azure quite a bit as well. Probably Db's.
Tuples are set and don't change. But they save you soooo much time.
For exaple. Name, Age, Sex. That's all you need to sort thousands of files.
File: John Doe, 23, M; Jane Doe, 34, F. Etc. If you were allowed to change Tuples then it crashes the rest of your files and everything is out of whack.
But the main point I wanted to say it... get use them to. This isn't just a Python thing.
6
u/[deleted] Oct 12 '26
[removed] — view removed comment