adding elements to python tuples

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Uwe Mayer

    adding elements to python tuples

    Hi,

    is it possible to append new elements to a tuple? I know tuples are
    immutable and that this would mean to create a new tuple with one more
    element, but how do you do it?

    i.e. i have (1,2,3) and want to append 4:
    (1,2,3,4) instead of ((1,2,3),4)

    I wanted to use it as a return value of a function and an assignment, but:

    (a,b,c),d = myfunc()

    doesn't look nice to me. I intended to have

    a,b,c,d = myfunc()

    Thanks for any suggestions.
    Ciao
    Uwe
    --

  • Erik Max Francis

    #2
    Re: adding elements to python tuples

    Uwe Mayer wrote:
    [color=blue]
    > is it possible to append new elements to a tuple? I know tuples are
    > immutable and that this would mean to create a new tuple with one more
    > element, but how do you do it?[/color]

    Just use the + operator:
    [color=blue][color=green][color=darkred]
    >>> a = (1, 2, 3)
    >>> a + (4,)[/color][/color][/color]
    (1, 2, 3, 4)[color=blue][color=green][color=darkred]
    >>> a[/color][/color][/color]
    (1, 2, 3)[color=blue][color=green][color=darkred]
    >>> a += (4, 5)
    >>> a[/color][/color][/color]
    (1, 2, 3, 4, 5)

    --
    __ Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
    / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
    \__/ Here day fights with night.
    -- (the last words of Victor Hugo)

    Comment

    • duikboot

      #3
      Re: adding elements to python tuples

      Maybe you could use this?
      [color=blue][color=green][color=darkred]
      >>> d=(1,2,3,4)
      >>> e=5,
      >>> d=d+e
      >>> d[/color][/color][/color]
      (1, 2, 3, 4, 5)


      Regards,

      Arjen


      "Uwe Mayer" <merkosh@hadiko .de> schreef in bericht
      news:bugels$6u$ 1@news.rz.uni-karlsruhe.de...[color=blue]
      > Hi,
      >
      > is it possible to append new elements to a tuple? I know tuples are
      > immutable and that this would mean to create a new tuple with one more
      > element, but how do you do it?
      >
      > i.e. i have (1,2,3) and want to append 4:
      > (1,2,3,4) instead of ((1,2,3),4)
      >
      > I wanted to use it as a return value of a function and an assignment, but:
      >
      > (a,b,c),d = myfunc()
      >
      > doesn't look nice to me. I intended to have
      >
      > a,b,c,d = myfunc()
      >
      > Thanks for any suggestions.
      > Ciao
      > Uwe
      > --
      >[/color]


      Comment

      Working...