Skip to content
Advertisement

Add variables to tuple

I am creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB.

I am taking information from the user and store it in variables. Can I add these variables into a tuple? Can you please help me with the syntax?

I only need the tuple to enter info into the DB. Once the information is added to the DB, should I delete the tuple? I mean I don’t need the tuple anymore.

Advertisement

Answer

Tuples are immutable; you can’t change which variables they contain after construction. However, you can concatenate or slice them to form new tuples:

a = (1, 2, 3)
b = a + (4, 5, 6)  # (1, 2, 3, 4, 5, 6)
c = b[1:]  # (2, 3, 4, 5, 6)

And, of course, build them from existing values:

name = "Joe"
age = 40
location = "New York"
joe = (name, age, location)
Advertisement