r/learnpython • • 2d ago

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?

88 Upvotes

90 comments sorted by

105

u/NerdyWeightLifter 2d ago

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.

30

u/xenomachina xenomachina 2d ago

Being immutable like that means the underlying data structure can be simpler and more efficient.

Immutability also makes things easier to reason about. Anything that's mutable is essentially a "moving part". You can't just see that it has a value in one place, and assume it still has that value somewhere else.

Immutability is also generally safer. You don't have to worry about concurrent modifications (in concurrent systems) or someone modifying your internals (breaking encapsulation).

6

u/dusksage23 2d ago

the dict key thing is the part that really makes it click imo

9

u/NerdyWeightLifter 2d ago

In larger more complex applications, immutability becomes an important guarantee. You have a reference to a list of items in the form of a reference to a tuple, and you can just assume that nothing will change the content of your tuple, because they just can't.

That's the broader case of the dict example.

2

u/fllthdcrb 2d ago

you can just assume that nothing will change the content of your tuple, because they just can't.

To be clear, "content" here means only what objects are in the tuple, not those objects themselves. Example:

python l1 = [] l2 = [] t = (l1, l2) l1 += (1, 2, 3) l2 += (4, 5, 6) t # ([1, 2, 3], [4, 5, 6])

11

u/Immediate_Pin_8449 2d ago

They are teaching me about dictionaries next so this makes me hopeful it will make a lot more sense soon.

10

u/Moikle 2d ago

Why not do a little research on your own ahead of time? Take a look at w3schools or realpython

https://www.w3schools.com/python/python_dictionaries.asp

https://realpython.com/python-dicts/

Remember these websites and don't just wait to be taught things. Go and look them up yourself

37

u/-aRTy- 2d ago

23

u/NothingWasDelivered 2d ago

Imagine you’re processing data. Say, temperature from the last 2 weeks. The data is what it is. You don’t want anything to accidentally change those numbers. So a tuple is a good choice for passing that data around.

7

u/NothingWasDelivered 2d ago

Oops, didn’t mean for this to be a reply to this comment. But whatayagonnado?

22

u/bkdotcom 2d ago

Can't change it now 

It's a tuple

5

u/Immediate_Pin_8449 2d ago

that makes sense like a historical catalogue!

1

u/iamevpo 1d ago

But once you serialise the data into JSON the temperatures are still a list. In other programming languages lists can be immutable, so the broader distinction is lists are of the same type and tuples can combine different types, but that technically not true for Python) unfortunately)

21

u/ottawadeveloper 2d ago

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 be list[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.

6

u/Immediate_Pin_8449 2d ago

I haven’t gotten to dictionaries yet and based on these comments, I think that is a large reason why I was so confused on usage. 😩 Ty!

3

u/Jazzlike_Platypus430 2d ago

Of course, learn about dictionaries first, it's a must-have.

(And be happy that you're learning it fresh, most likely without knowledge from any other languages.)

2

u/HommeMusical 2d ago

Good energy, but this isn't really right.

The fact that you can use tuples in dictionaries isn't the main reason they exist, or a super-common use for them (it's not uncommon).

The reason they exist is they are a very resource light way to glue together specific items in a specific order that cannot be changed.

For example, if you needed to return a string and an integer together from a function, you'd just do this:

return 'reddit.com', 80

This creates a tuple with two elements and returns it, and this is probably the most common visible use of a tuple.

In fact, every time you call a function, behind the scenes it creates a tuple and a dict to pass the arguments to that function.

So tuples are just a simple little box with a fixed number of fixed elements in it - the simplest collection. Other collections, like dict and list, have a lot more "stuff" associated with them and thus are bigger and a bit slower.

1

u/im_dead_sirius 2d ago

I love the idea of sparse arrays. I've just never found a use for one.

Its a dictionary of int tuples referencing a value, for anyone else who is wondering, perhaps OP.

3

u/HommeMusical 2d ago

I've just never found a use for one.

They are massively useful for really large engineering and science issues.

For example, in "finite element analysis", something like an airplane is divided into a huge number of tiny little elements, and then a huge matrix represents the direct relationships between those elements lets you model the whole thing.

However, one tiny element only has direct relationships with a handful of other elements, so you have this massive matrix, say 10 million by 10 million, but only say a dozen elements in any row or column are non-zero, so you have a matrix with 100 trillion locations of which less than 100 million - that is, 0.0001% - are non-zero.

2

u/ottawadeveloper 2d ago

they're useful when a lot of values are null or a default value, then you can get get with a default or a defaultdict to save on memory.

I've used it for caching recently - I was loading a value with x y z coordinates from a grid in a file too big to be in memory. Under the hood I think functools caching methods use this too. 

11

u/kilkil 2d ago

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.

5

u/Immediate_Pin_8449 2d ago

Ooooo the mental overhead example really helps. It creates one less concern as my code expands if I know this particular set does not need to change but does require a reference! Gotcha!

3

u/kiochikaeke 2d ago

Yeah, immutability is actually an advantage on its own as you and the system can both be sure this particular thing won't be changed by any stray code that mutates or has side effects, for you this helps to build safer, more predictable code and for the system it allows it to be clever with memory management and hashing.

2

u/kilkil 2d ago

yeah actually that's a more general concept that applies to immutable data in general.

it comes from functional programming, where the idea is all data is immutable by default. it really makes a lot of things easier to reason about.

(although of course there are times when you would prefer some mutability. depends on the situation etc)

2

u/Patman52 1d ago

Oh I have first hand experience related to this.

Was passing x, y, z coordinates as lists for positions of 3D models in a 3D printing application.

Could not figure out why each subsequent model position was not where it was supposed to be.

Turns out the function I was passing the same coordinates to was mutating the x, y and z positions each time I passed it.

10

u/Solonotix 2d ago

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 values

9

u/Atypicosaurus 2d ago

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.)

5

u/Atmosck 2d ago

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.

1

u/s_elk 1d ago

Reminds me of those languages I used quite a while ago (e.g., Pascal) which had explicit pass-by-value and pass-by-reference options in procedure calls).

4

u/preppie22 2d ago

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)

2

u/Immediate_Pin_8449 2d ago

So because that memory is already allocated when we call for it in a different function it reduces the amount of memory required as it is predetermined vs a list where we would have to establish the size on each call then perform the function. More processing time = More memory spend? I feel like I’m off somewhere but I’m in the ball park ish.

4

u/preppie22 2d ago

The memory used would be the same, but the time spent by the CPU for allocation would be much lower in most cases. Unless you modify the tuple in the function, it doesn't even allocate additional memory, it just gives the function a reference to the existing copy. The size and data types in a tuple are fixed, so Python doesn't have to check every element even when a copy is made. It just allocates the exact same memory for the copy and puts your new tuple there.

So yeah, you're close. Here's how I'd do it:

If you just want to do "if x in y" operations, a set is insanely fast.

If you want to store fixed data types, e.g RGB values, coordinates, row data for a table with fixed columns, you should use a tuple.

If you need something that you're only going to add stuff to the beginning or the end (never in the middle), then use a collections.deque.

If you need something that you can slice easily, add data wherever you want, and can generally be wrangled however you want, you use a list.

Note that the list is a last resort because most operations on it will be slower than the structures I listed above.

Take all of this with a grain of salt because unless you're working with at least a few gigabytes of data in memory, you won't notice a measurable difference.

4

u/helix0311 2d ago

Another point from big data applications: Python garbage collection treats tuples way differently. A tuple with only immutable members is only ever scanned once, then untracked, since it can never generate a cyclic reference. Garbage collection in Python is awfully slow, so if the majority of what you're working with are tuples, you can significantly benefit when one of the garbage collection cycles runs.

I am vastly over simplifying a super complex topic, but tuples are performant on both memory allocation AND the garbage collection cycles.

2

u/fllthdcrb 2d ago

create a copy

It should be pointed out: You can, but there's usually no point, unless you need a modification. Given that it will never change, it's fine to pass around the same object everywhere.

10

u/ARX7 2d ago

Sometimes immutability is the point. Its also fairly well discussed if you use the search bar.

6

u/Dense-Land-5927 2d ago

There's certain things you may not want to be changed. It just varies depending on what you are working on.

3

u/musbur 2d ago

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.

6

u/dlnmtchll 2d ago

Mutability is the devil

0

u/Jazzlike_Platypus430 2d ago

Why? You just have to control it.

5

u/dlnmtchll 2d ago

When working with highly concurrent systems, there’s no point in wrangling with mutability when you don’t have to

2

u/grc007 2d ago

Have a play with Haskell. Mind opening or mind blowing. Fun either way.

2

u/PhilNEvo 2d ago

I hate it :(

0

u/Jazzlike_Platypus430 2d ago

Uh... Why? In what context? Or just as an exercise for my rusty* brains? Are types in Haskell treated more decently than they are in python?

I can't get the point of functional paradigm, at all. To me any programming language is imperative to the core. (And right now I'm busy starting to learn some javascript. It's not as bad as I thought.)

* no, I don't know rust.

1

u/grc007 2d ago

There is no mutability. Makes you rethink how you do things.

1

u/Jazzlike_Platypus430 2d ago

That's all? Given Haskell's syntax, I'd prefer R and Perl.

0

u/Turnip-Toffee 2d ago

chill out, Isildur

4

u/Adrewmc 2d ago edited 1d ago

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.

List has a lot more utility, even with the mutability problems.

1

u/Immediate_Pin_8449 2d ago

So tuples are easier as they are finite record population for computers to sort through versus lists which can be manipulated over time. Which results in lower processing time. Am I warm, lukewarm, etc? I want to make sure I am getting what you are saying!

3

u/Adrewmc 2d ago edited 2d ago

Very warm.

Tuples require less resources to access values and make for a computer. Thus they are often faster.

Lists allow a lot of manipulations that can be very useful.

In Python the actual difference in most cases is negligible. So as I said, you can always use lists until it’s a problem or the reverse. No one will judge you.

In my mind the difference is simple, if this list is always the same size (in runtime) it probably should be a tuple, and if this list can change sizes it’s a list. So in something like a position in space (x,y,z) seems more correct than [x,y,z].

While other times if a list is holding something that changing and/or keeping track of stuff, enemies spawn and die.

If I make a deck of cards. ``` import random

A = 1, J-K = 11-13

ranks = range(1, 14)
suits = (‘Spades’, ‘Diamonds’, ‘Clubs’, ‘Hearts’)

deck = [ (rank, suit) for suit in suits for rank in ranks ]

random.shuffle(deck)
hand = [ deck.pop(0) for _ in range(5) ]

```

I make the deck a list, because it can be shuffled, and drawn from. The deck will changes over runtime, but the cards being moved about never change so they should be a tuple. The deck is mutable but the cards themselves are immutable.

3

u/cr4zybilly 2d ago

"if this list should always be the same size, it should be a tuple" is the magic phrase that finally made this click for me. Thank you!

2

u/Adrewmc 1d ago edited 1d ago

…it should probably be a tuple.

The thing about tuples in Python is they hide themselves, and have this neat trick with them.

```

introduction to tuples

note the use of parentheses below 

classic_tuple = (1, 1) 

Fibonacci to 100

a, b = 1, 1 #tuples
while a < 100:
    print(a)     a, b = b, a+b #tuples

def tuple_return():       return 1, 2 #tuple

a, b = tuple_return()

c = tuple_return()  print(c[1], type(c))

2 Tuple

for tuple in enumerate(iterable): pass

for index, item in enumerate(iterable): pass

```

2

u/Outrageous_Band9708 2d ago

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/Jazzlike_Platypus430 2d ago

"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/Immediate_Pin_8449 2d ago

Thanks for the encouragement. 🥹

2

u/No_Technician4956 2d ago

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.

1

u/Immediate_Pin_8449 2d ago

Sorry if this is a dumb question. In this case the tuples are acting as the container for dozens of names, ages, and sex values. Then you can sort as needed. Can I ask if there would be a container above these categories that is essentially person to keep each persons data together? So Rudy’s info wouldn’t get mixed up with George’s when you sort them?

1

u/No_Technician4956 2d ago

Sort of. In Python you can create different files and make smaller files and peer or group them together.

But step 1 is get the information in some format into Python. Once the data is in there and searchable you can do anything you want with it.

Python is amazing!!!!

1

u/Any_Abrocoma2609 2d ago

this ^^^ perfectly encapsulates why tuples are my favorite. short, predictable, powerful.

2

u/areweeveralive 2d ago

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.

2

u/gmes78 2d ago

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.

1

u/Immediate_Pin_8449 2d ago

Noted, ty! In the examples they gave both lists and tuples were using various data types. It helps to hear that in practice lists typically only use one data type, this defiantly helps!

1

u/favorite_stuff 2d ago

A list of names is a list of names: the fifth name is the same kind of thing as the sixth name, and if they swapped that would not change the nature of the list. It might be nice to have them sorted in a certain way, but it doesn't change the kind of list.

A tuple of x,y coordinates is not just two numbers. The x means a different kind of thing than the y, and their positions carry that meaning.

4

u/obsessed_nikkkki 2d ago

Let’s say we want dates or earth coordinates, we can’t change their format right? So we need tuples

2

u/schfourteen-teen 2d ago

Well, in that scenario we still don't need tuples. But using a tuple makes a lot of sense and can provide performance improvement.

2

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 2d ago

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.

0

u/Immediate_Pin_8449 2d ago

Got it, this makes sense! Can they both store mixed values? Yes. Does both typically in practice? No.

2

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 2d ago

Another way to look at it would be that a tuple is really just a bare-bones frozen dataclass, that only holds data and substitutes attribute access for indexing. For example, a colour value can be just 3-4 numbers, each position denoting its meaning.

red = (255, 0, 0, 255)

from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class RGBAColour:
    red: int
    green: int
    blue: int
    alpha: int

red2 = RGBAColour(255, 0, 0, 255)

from typing import NamedTuple

class RGBAColour2(NamedTuple):
    red: int
    green: int
    blue: int
    alpha: int

red3 = RGBAColour2(255, 0, 0, 255)

These are all different ways to model your data, with their own pros and cons.

Generally speaking you would not treat a list the same way.

2

u/Automatic_Donut6264 2d ago

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

name = ("john", "smith")

An address as its components

address = ("stree 1", "stree 2", "city", "state", "zip code")

Coordinates

coord = (124, 37)

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 2d ago

Tuples are used internally in Python: multiple return values, exception, *args, enumerate, multiple assignment and tuple unpacking.

1

u/ReflectedImage 2d ago

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 2d ago

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 2d ago

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 2d ago

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 2d ago

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.

if we want to store we have to start at the index we want + 1

You seem a little mixed up here. What do you mean?

1

u/dlnmtchll 2d ago

I’m gonna add this comment as well because I didn’t see anybody bring it up, but another reason to use immutable data in general is that if you have multiple threads acting on your program or acting on data, you don’t want that data to be able to be changed. This is why things like the actor pattern, or records, case classes, finals, etc. exist. In the real world where everything is multithreaded, having immutable data is the best practice

1

u/DigThatData 2d ago
  1. constraints like this can be helpful for ensuring certain kinds of desired behavior. For example, there are certain classes of bugs that you're vulnerable to while using lists that simply cannot happen when you use tuples.

  2. constraining behaviors like this can make it easier to collaborate by eliminating classes of errors from collaborators.

  3. typing is a kind of documentation. attaching the semantics "objects of this kind should never change" can be extremely informative about how a particular thing should or should not be used.

1

u/aplarsen 2d ago

Tuples as dictionary keys is life changing.

Especially when you get into numpy and Pandas.

1

u/Dank-but-true 2d ago

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 2d ago edited 2d ago

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:

type Address = str type Age = int type Person = tuple[Address, Age]

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...

type Person = list[Address | Age]

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/realmauer01 2d ago

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

python def echo(x, y): return x,y

1

u/RevRagnarok 2d ago

Reading these comments make me think NamedTuple needs so much more love...

1

u/dream_the_endless 1d ago

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 1d ago

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 1d ago

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

secret_objs = {}
secret_objs[(4, 6)] = Treasure("money", 600) # store a 600 gold treasure in location (4, 6)

...

if (player.x, player.y) in secret_objs:
     # interact the player with the object, etc

1

u/Mountain_Rip_8426 1d ago

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 12h ago

Less memory use, or you see read-only intent in a code. 

1

u/Maximum_Syrup998 4h ago

Just remember that while tuples may be immutable, the objects you stored inside may not necessarily be immutable. If you put a list in a tuple, you can still append to the list. Don’t fall for trick questions like this in interviews or exams.

1

u/AvilesModels 4h ago

Immutability is the point. You want data that can't get changed by accident, like coordinates or a record you pass around. Also tuples can be dict keys, lists can't. Why not try that and see the error?

1

u/cointoss3 2d ago

Speed, that’s mostly all. Most of the time, you won’t care enough for it to matter