375

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
amit
  • 10,133
  • 22
  • 72
  • 121

9 Answers9

497

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)
John R Perry
  • 3,916
  • 2
  • 38
  • 62
John Millikin
  • 197,344
  • 39
  • 212
  • 226
  • i only need these tuples for adding to the db after user input. so should i destruct these tuples after updation to the db is completed? – amit Sep 04 '09 at 18:42
  • 8
    You need not destruct the tuples after updating the db. If they go out of scope they should be garbage collected. – Justin Standard Sep 04 '09 at 18:56
  • 1
    To add a string to the tuple without breaking the string itself check https://stackoverflow.com/a/16449189 – Enzo Ferey Dec 24 '17 at 19:24
  • 1
    Just to add on, `a = ()`, and `b= a + (5)`, leads to b = 5, therefore, `b= a + (5,)`, would leads to `b = (5,)`; a tuple. – o12d10 Jan 21 '19 at 17:37
  • It is worth mentioning that one can also *multiply* tuples : `4*(1,)` gives `(1, 1, 1, 1)`. This may proves useful e.g. if you need to complement several tuples at a fixed length (`tup+(lmax-len(tup))*("",)`). – Skippy le Grand Gourou Jul 16 '21 at 10:25
267

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)
phoenix
  • 7,988
  • 6
  • 39
  • 45
Daniel
  • 2,956
  • 2
  • 15
  • 12
  • 24
    In this example case, one can also do: `t = ()` then `t += (1,)` – Douglas Denhartog Jan 20 '15 at 23:24
  • 3
    What benefit is there to including the trailing comma? – Splic May 25 '18 at 20:16
  • 20
    The trailing comma si necessary for the singleton to avoid confusion between an element in parentheses. Plain parentheses are used in order of operations, so (7) is just 7. But (7,) is a one-element tuple where the element is 7. Likewise, 3 * ( 7+8) = 45, but 3 * (7+8,) = (15, 15, 15) -- does that make sense? – Daniel May 27 '18 at 03:28
  • 3
    As for the multi-element tuples, the trailing comma is 100% optional. Including it kind of signifies "this is a tuple, I know it's a tuple, I know how tuples work, and I know I can do that." But no comma might seem more natural. Idk. Up to you. – Daniel May 27 '18 at 03:29
  • 1
    I think its important to note that tuples are immutable - they cannot actually be modified. What this solution does is *create a new tuple* based on two *existing* tuples. – That1Guy Jan 16 '19 at 20:58
65

In Python 3, you can use * to create a new tuple of elements from the original tuple along with the new element.

>>> tuple1 = ("foo", "bar")
>>> tuple2 = (*tuple1, "baz")
>>> tuple2
('foo', 'bar', 'baz')

The byte code is almost the same as tuple1 + ("baz",)

Python 3.7.5 (default, Oct 22 2019, 10:35:10) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...     tuple1 = ("foo", "bar")
...     tuple2 = (*tuple1, "baz")
...     return tuple2
... 
>>> def g():
...     tuple1 = ("foo", "bar")
...     tuple2 = tuple1 + ("baz",)
...     return tuple2
... 
>>> from dis import dis
>>> dis(f)
  2           0 LOAD_CONST               1 (('foo', 'bar'))
              2 STORE_FAST               0 (tuple1)

  3           4 LOAD_FAST                0 (tuple1)
              6 LOAD_CONST               3 (('baz',))
              8 BUILD_TUPLE_UNPACK       2
             10 STORE_FAST               1 (tuple2)

  4          12 LOAD_FAST                1 (tuple2)
             14 RETURN_VALUE
>>> dis(g)
  2           0 LOAD_CONST               1 (('foo', 'bar'))
              2 STORE_FAST               0 (tuple1)

  3           4 LOAD_FAST                0 (tuple1)
              6 LOAD_CONST               2 (('baz',))
              8 BINARY_ADD
             10 STORE_FAST               1 (tuple2)

  4          12 LOAD_FAST                1 (tuple2)
             14 RETURN_VALUE

The only difference is BUILD_TUPLE_UNPACK vs BINARY_ADD. The exact performance depends on the Python interpreter implementation, but it's natural to implement BUILD_TUPLE_UNPACK faster than BINARY_ADD because BINARY_ADD is a polymorphic operator, requiring additional type calculation and implicit conversion.

Yang Bo
  • 3,586
  • 3
  • 22
  • 35
52

Another tactic not yet mentioned is using appending to a list, and then converting the list to a tuple at the end:

mylist = []
for x in range(5):
    mylist.append(x)
mytuple = tuple(mylist)
print mytuple

returns

(0, 1, 2, 3, 4)

I sometimes use this when I have to pass a tuple as a function argument, which is often necessary for the numpy functions.

ehontz
  • 1,110
  • 10
  • 7
  • 3
    It is useful to know that the reverse of this, i.e. `list(someTuple)` works too. The two object types are apparently interchangable – khaverim Sep 08 '14 at 20:41
  • Not really interchangeable, I think the conversion from tuple to list will copy all elements in the list, so there are definitely place to avoid it – gbtimmon Nov 13 '16 at 04:00
10

It's as easy as the following:

info_1 = "one piece of info"
info_2 = "another piece"
vars = (info_1, info_2)
# 'vars' is now a tuple with the values ("info_1", "info_2")

However, tuples in Python are immutable, so you cannot append variables to a tuple once it is created.

mipadi
  • 398,885
  • 90
  • 523
  • 479
9

" once the info is added to the DB, should I delete the tuple? i mean i dont need the tuple anymore."

No.

Generally, there's no reason to delete anything. There are some special cases for deleting, but they're very, very rare.

Simply define a narrow scope (i.e., a function definition or a method function in a class) and the objects will be garbage collected at the end of the scope.

Don't worry about deleting anything.

[Note. I worked with a guy who -- in addition to trying to delete objects -- was always writing "reset" methods to clear them out. Like he was going to save them and reuse them. Also a silly conceit. Just ignore the objects you're no longer using. If you define your functions in small-enough blocks of code, you have nothing more to think about.]

S.Lott
  • 384,516
  • 81
  • 508
  • 779
4

As other answers have noted, you cannot change an existing tuple, but you can always create a new tuple (which may take some or all items from existing tuples and/or other sources).

For example, if all the items of interest are in scalar variables and you know the names of those variables:

def maketuple(variables, names):
  return tuple(variables[n] for n in names)

to be used, e.g, as in this example:

def example():
  x = 23
  y = 45
  z = 67
  return maketuple(vars(), 'x y z'.split())

of course this one case would be more simply expressed as (x, y, z) (or even foregoing the names altogether, (23, 45, 67)), but the maketuple approach might be useful in some more complicated cases (e.g. where the names to use are also determined dynamically and appended to a list during the computation).

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
3

I'm pretty sure the syntax for this in python is:

user_input1 = raw_input("Enter Name: ")
user_input2 = raw_input("Enter Value: ")
info = (user_input1, user_input2)

once set, tuples cannot be changed.

Jon W
  • 15,480
  • 6
  • 37
  • 47
-1

If you tryna use a separate function then try either of these:

def insert_value_at_beginning(input_tuple, value_to_insert):
    return (value_to_insert,) + input_tuple

input_tuple = (2, 3, 4)
value_to_insert = 1
output_tuple = insert_value_at_beginning(input_tuple, value_to_insert)
print(output_tuple)  # Expected output: (1, 2, 3, 4)

OR

def insert_value_at_the_end(input_tuple, value_to_insert):
    return input_tuple + (value_to_insert,)

input_tuple = (2, 3, 4)
value_to_insert = 1
output_tuple = insert_value_at_the_end(input_tuple, value_to_insert)
print(output_tuple)  # Expected output: (2, 3, 4, 1)

OR simply try either of these:

input_tuple = (2, 3, 4)
value_to_insert = 1
new = (value_to_insert, ) + input_tuple
print(new)  # Expected output: (1, 2, 3, 4)

OR:

input_tuple = (2, 3, 4)
value_to_insert = 1
new = input_tuple + (value_to_insert, )
print(new)  # Expected output: (2, 3, 4, 1)