376

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.

9 Answers 9

498

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)
5
  • 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 4, 2009 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. Sep 4, 2009 at 18:56
  • 1
    To add a string to the tuple without breaking the string itself check stackoverflow.com/a/16449189
    – Enzo Ferey
    Dec 24, 2017 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, 2019 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))*("",)). Jul 16, 2021 at 10:25
269

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)
5
  • 24
    In this example case, one can also do: t = () then t += (1,) Jan 20, 2015 at 23:24
  • 3
    What benefit is there to including the trailing comma?
    – Splic
    May 25, 2018 at 20:16
  • 22
    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, 2018 at 3: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, 2018 at 3: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, 2019 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.

3
  • 10
    This is 10x slower than tuple1 + ("baz",). Dec 6, 2018 at 1:42
  • I like this but as stated, this is slower than simply using +, I did test.
    – NelsonGon
    May 21, 2021 at 6:03
  • 2
    The performance difference is CPython implementation specific. The two functions have similar performance on PyPy.
    – Yang Bo
    May 27, 2021 at 5:40
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.

2
  • 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 8, 2014 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, 2016 at 4: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.

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.]

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).

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.

-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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.