Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Variables to Tuple

Tags:

python

tuples

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.

like image 542
amit Avatar asked Sep 04 '09 18:09

amit


People also ask

How do you add variables to a tuple?

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.

Can we add value in 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.

Can I add elements to a tuple Python?

For now, lets just say tuples are immutable in general. You can't add elements to a tuple because of their immutable property.

Can you use += for tuples?

That's right: Adding a list to a tuple with + doesn't work. But if we use +=, it does.


2 Answers

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) 
like image 168
John Millikin Avatar answered Sep 28 '22 01:09

John Millikin


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) 
like image 32
Daniel Avatar answered Sep 28 '22 02:09

Daniel