I am learning Python and 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.
What I am Doing: 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?
Also if there is an efficient way of doing this, please share...
EDIT Let me edit this question a bit...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.
As we know that Tuples are immutable objects in Python. We cannot perform addition, deletion, modification operations on tuples once created. So, in order to add variables or items in a tuple, we have to create a new tuple instead of modifying the original tuple.
In Python, since tuple is immutable, you cannot update it, i.e., you cannot add, change, or remove items (elements) in tuple . tuple represents data that you don't need to update, so you should use list rather than tuple if you need to update it.
For now, lets just say tuples are immutable in general. You can't add elements to a tuple because of their immutable property.
That's right: Adding a list to a tuple with + doesn't work. But if we use +=, it does.
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)
You can start with a blank tuple with something like t = ()
. You can add with +
, but you have to add another tuple. If you want to add a single element, make it a singleton: t = t + (element,)
. You can add a tuple of multiple elements with or without that trailing comma.
>>> t = () >>> t = t + (1,) >>> t (1,) >>> t = t + (2,) >>> t (1, 2) >>> t = t + (3, 4, 5) >>> t (1, 2, 3, 4, 5) >>> t = t + (6, 7, 8,) >>> t (1, 2, 3, 4, 5, 6, 7, 8)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With