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

7

u/drenzorz Mar 27 '23

example: tuples can be hashed and used as dictionary keys unlike lists.

board = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

cells = {
    (i, j) : board[i][j]
    for i in range(3)
    for j in range(3)
}

4

u/Other-Rabbit1808 Mar 27 '23

So what I think this is doing is assigning { (1-3,1-3) : 1-9 } in a dictionary? I've never seen for loops ordered in this way. Would this be called something like a dictionary comprehension?

2

u/drenzorz Mar 27 '23 edited Mar 27 '23

It is (though it is 0-2 not 1-3) . The for loops are like this because its nested, but of course it doesn't have to be.

square_map = { x : x*x for x in numbers}