r/learnpython • • 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

64 comments sorted by

View all comments

138

u/carcigenicate Carcigenicate Mar 27 '23 edited Mar 30 '23

The simplest example would likely be just "returning two values from a function":

def divmod(x, y):
    return x // y, x % y

quotient, remainder = divmod(21, 5)

, is used to create a tuple. The tuple is being used here to wrap two integers so they can be returned together. Just being able to group data is often useful, and tuples are a straightforward way to do that.

25

u/hidazfx hlafaille Mar 27 '23

Another one that people don't realize is actually a tuple is enumerate() when using a for loop. enumerate() lets you access the position and the actual value at each iteration.

9

u/[deleted] Mar 27 '23

Doesn't enumerate return an Enumerate object, rather than a tuple ?

9

u/hidazfx hlafaille Mar 27 '23

Never mind, I am wrong! Thank you for correcting me lol.

4

u/[deleted] Mar 27 '23

Heh no worries. It's use case is pretty similar to tuple :)

5

u/Rawing7 Mar 27 '23

Right, but looping over the enumerate object gives you tuples.