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

11

u/jimtk IdontChat Mar 27 '23

Tuple are groups of simple data like list, but they are immutable (you can't change the values inside), smaller and faster.

def pixel_up_right(x,y):
     return x+1, y+1    # <=== that's a tuple

# coordinates of cities is a tuple!
cities_coord_name = {
       (45.4826668,-73.6215805): Montreal
       (40.6974034,-74.1197614): New-York
       }                          

When you read a record from an sqlite database (as an example) it is returned in a list of tuple.

    con, cur = self._con_cur()
    cur.execute(DB.SQL_SEARCH_BY_ID, (an_id,))
    rows = cur.fetchall()
    con.close()
    print(rows)      <<< rows are list of tuples

[ (1, "jim", "preston", "555-1212"),
   (2, "count", "Dracula",  "111-1111")]

1

u/espero Mar 27 '23

Salt: Salty

Sugar: Sweet

Immutable facts of life

2

u/jimtk IdontChat Mar 27 '23

[(Salt, Salty), (Sugar, Sugary)].

That's probably why it is very difficult to create an immutable user defined object in Python. :)