Flatten a list/tuple and Call a function with tuples

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

    Flatten a list/tuple and Call a function with tuples

    Hi,

    I am wondering how do I 'flatten' a list or a tuple? For example, I'd
    like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].

    Another question is how do I pass a tuple or list of all the
    aurgements of a function to the function. For example, I have all the
    arguments of a function in a tuple a=(1,2,3). Then I want to pass each
    item in the tuple to a function f so that I make a function call
    f(1,2,3). In perl it is a given, but in python, I haven't figured out
    a way to do it. (Maybe apply? but it is deprecated?)

    Thanks,
    cg

  • kyosohma@gmail.com

    #2
    Re: Flatten a list/tuple and Call a function with tuples

    On Jul 25, 9:50 am, beginner <zyzhu2...@gmai l.comwrote:
    Hi,
    >
    I am wondering how do I 'flatten' a list or a tuple? For example, I'd
    like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
    >
    Another question is how do I pass a tuple or list of all the
    aurgements of a function to the function. For example, I have all the
    arguments of a function in a tuple a=(1,2,3). Then I want to pass each
    item in the tuple to a function f so that I make a function call
    f(1,2,3). In perl it is a given, but in python, I haven't figured out
    a way to do it. (Maybe apply? but it is deprecated?)
    >
    Thanks,
    cg
    I'm not sure about the first question, but as for the second, you
    could do a few different things. You could just pass the tuple itself
    into the function and have the tuple unpacked inside the function.

    <code>

    f(a)

    def f (tuple):
    x,y,z = tuple

    </code>

    You could also pass the elements of the tuple in:

    f(a[0], a[1], a[2])

    That would do it the way you describe in your post.

    Mike

    Comment

    • Stargaming

      #3
      Re: Flatten a list/tuple and Call a function with tuples

      On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
      Hi,
      >
      I am wondering how do I 'flatten' a list or a tuple? For example, I'd
      like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
      A recursive function, always yielding the first element of the list,
      could do the job. See the ASPN Python Cookbook for a few implementations .

      query=flatten&s ection=PYTHONCK BK&type=Subsect ion
      Another question is how do I pass a tuple or list of all the aurgements
      of a function to the function. For example, I have all the arguments of
      a function in a tuple a=(1,2,3). Then I want to pass each item in the
      tuple to a function f so that I make a function call f(1,2,3). In perl
      it is a given, but in python, I haven't figured out a way to do it.
      (Maybe apply? but it is deprecated?)
      >>def foo(a, b, c): print a, b, c
      ....
      >>t = (1, 2, 3)
      >>foo(*t)
      1 2 3

      Have a look at the official tutorial, 4.7.4 http://www.python.org/doc/
      current/tut/node6.html#SECT ION006740000000 000000000
      Thanks,
      cg
      HTH,
      Stargaming

      Comment

      • beginner

        #4
        Re: Flatten a list/tuple and Call a function with tuples

        On Jul 25, 10:19 am, Stargaming <stargam...@gma il.comwrote:
        On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
        Hi,
        >
        I am wondering how do I 'flatten' a list or a tuple? For example, I'd
        like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
        >
        A recursive function, always yielding the first element of the list,
        could do the job. See the ASPN Python Cookbook for a few implementations .http://aspn.activestate.com/ASPN/search?
        query=flatten&s ection=PYTHONCK BK&type=Subsect ion
        >
        Another question is how do I pass a tuple or list of all the aurgements
        of a function to the function. For example, I have all the arguments of
        a function in a tuple a=(1,2,3). Then I want to pass each item in the
        tuple to a function f so that I make a function call f(1,2,3). In perl
        it is a given, but in python, I haven't figured out a way to do it.
        (Maybe apply? but it is deprecated?)
        >def foo(a, b, c): print a, b, c
        ...
        >t = (1, 2, 3)
        >foo(*t)
        >
        1 2 3
        >
        Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
        current/tut/node6.html#SECT ION006740000000 000000000
        >
        Thanks,
        cg
        >
        HTH,
        Stargaming
        Hi Stargaming,

        I know the * operator. However, a 'partial unpack' does not seem to
        work.

        def g():
        return (1,2)

        def f(a,b,c):
        return a+b+c

        f(*g(),10) will return an error.

        Do you know how to get that to work?

        Thanks,
        cg


        Comment

        • kyosohma@gmail.com

          #5
          Re: Flatten a list/tuple and Call a function with tuples

          On Jul 25, 10:46 am, beginner <zyzhu2...@gmai l.comwrote:
          On Jul 25, 10:19 am, Stargaming <stargam...@gma il.comwrote:
          >
          >
          >
          On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
          Hi,
          >
          I am wondering how do I 'flatten' a list or a tuple? For example, I'd
          like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
          >
          A recursive function, always yielding the first element of the list,
          could do the job. See the ASPN Python Cookbook for a few implementations .http://aspn.activestate.com/ASPN/search?
          query=flatten&s ection=PYTHONCK BK&type=Subsect ion
          >
          Another question is how do I pass a tuple or list of all the aurgements
          of a function to the function. For example, I have all the arguments of
          a function in a tuple a=(1,2,3). Then I want to pass each item in the
          tuple to a function f so that I make a function call f(1,2,3). In perl
          it is a given, but in python, I haven't figured out a way to do it.
          (Maybe apply? but it is deprecated?)
          >>def foo(a, b, c): print a, b, c
          ...
          >>t = (1, 2, 3)
          >>foo(*t)
          >
          1 2 3
          >
          Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
          current/tut/node6.html#SECT ION006740000000 000000000
          >
          Thanks,
          cg
          >
          HTH,
          Stargaming
          >
          Hi Stargaming,
          >
          I know the * operator. However, a 'partial unpack' does not seem to
          work.
          >
          def g():
          return (1,2)
          >
          def f(a,b,c):
          return a+b+c
          >
          f(*g(),10) will return an error.
          >
          Do you know how to get that to work?
          >
          Thanks,
          cg
          As I mentioned, you can access the elements individually using square
          brackets. The following works:

          f(g()[0], g()[1], 10)

          But it's not clear. Unfortunately, I'm not seeing much else for tuple
          unpacking except the obvious:

          a,b=g()
          f(a,b,10)


          Mike

          Comment

          • beginner

            #6
            Re: Flatten a list/tuple and Call a function with tuples

            On Jul 25, 11:00 am, kyoso...@gmail. com wrote:
            On Jul 25, 10:46 am, beginner <zyzhu2...@gmai l.comwrote:
            >
            >
            >
            >
            >
            On Jul 25, 10:19 am, Stargaming <stargam...@gma il.comwrote:
            >
            On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
            Hi,
            >
            I am wondering how do I 'flatten' a list or a tuple? For example, I'd
            like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
            >
            A recursive function, always yielding the first element of the list,
            could do the job. See the ASPN Python Cookbook for a few implementations .http://aspn.activestate.com/ASPN/search?
            query=flatten&s ection=PYTHONCK BK&type=Subsect ion
            >
            Another question is how do I pass a tuple or list of all the aurgements
            of a function to the function. For example, I have all the arguments of
            a function in a tuple a=(1,2,3). Then I want to pass each item in the
            tuple to a function f so that I make a function call f(1,2,3). In perl
            it is a given, but in python, I haven't figured out a way to do it.
            (Maybe apply? but it is deprecated?)
            >def foo(a, b, c): print a, b, c
            ...
            >t = (1, 2, 3)
            >foo(*t)
            >
            1 2 3
            >
            Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
            current/tut/node6.html#SECT ION006740000000 000000000
            >
            Thanks,
            cg
            >
            HTH,
            Stargaming
            >
            Hi Stargaming,
            >
            I know the * operator. However, a 'partial unpack' does not seem to
            work.
            >
            def g():
            return (1,2)
            >
            def f(a,b,c):
            return a+b+c
            >
            f(*g(),10) will return an error.
            >
            Do you know how to get that to work?
            >
            Thanks,
            cg
            >
            As I mentioned, you can access the elements individually using square
            brackets. The following works:
            >
            f(g()[0], g()[1], 10)
            >
            But it's not clear. Unfortunately, I'm not seeing much else for tuple
            unpacking except the obvious:
            >
            a,b=g()
            f(a,b,10)
            >
            Mike- Hide quoted text -
            >
            - Show quoted text -
            Unfortunately f(g()[0], g()[1], 10) is calling g() twice. Sometimes
            this is not a good idea.
            a,b=g()
            f(a,b,10)
            would work until you want it to be an expression.

            Comment

            • Diez B. Roggisch

              #7
              Re: Flatten a list/tuple and Call a function with tuples

              beginner wrote:
              On Jul 25, 10:19 am, Stargaming <stargam...@gma il.comwrote:
              >On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
              Hi,
              >>
              I am wondering how do I 'flatten' a list or a tuple? For example, I'd
              like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
              >>
              >A recursive function, always yielding the first element of the list,
              >could do the job. See the ASPN Python Cookbook for a few
              >implementation s.http://aspn.activestate.com/ASPN/search?
              >query=flatten& section=PYTHONC KBK&type=Subsec tion
              >>
              Another question is how do I pass a tuple or list of all the aurgements
              of a function to the function. For example, I have all the arguments of
              a function in a tuple a=(1,2,3). Then I want to pass each item in the
              tuple to a function f so that I make a function call f(1,2,3). In perl
              it is a given, but in python, I haven't figured out a way to do it.
              (Maybe apply? but it is deprecated?)
              >>def foo(a, b, c): print a, b, c
              >...
              >>t = (1, 2, 3)
              >>foo(*t)
              >>
              >1 2 3
              >>
              >Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
              >current/tut/node6.html#SECT ION006740000000 000000000
              >>
              Thanks,
              cg
              >>
              >HTH,
              >Stargaming
              >
              Hi Stargaming,
              >
              I know the * operator. However, a 'partial unpack' does not seem to
              work.
              >
              def g():
              return (1,2)
              >
              def f(a,b,c):
              return a+b+c
              >
              f(*g(),10) will return an error.
              >
              Do you know how to get that to work?
              f(*(g() + (10,))

              Not the most beautiful solution, but it works.

              Diez

              Comment

              • Paul Rubin

                #8
                Re: Flatten a list/tuple and Call a function with tuples

                beginner <zyzhu2000@gmai l.comwrites:
                I know the * operator. However, a 'partial unpack' does not seem to work.
                A few other posters have mentioned ways around this, but you might ask
                yourself what coding situation makes you want to do this stuff in the
                first place. I won't say there's never a reason for it, but a lot of
                times, a list containing a mixture of scalars and lists/tuples is a
                sign that your underlying data representation is contorted. Things
                are logically single values or they are logically lists of values, and
                that mixed representation is often a sign that the item logically
                should be a list, and you're hairing up the program with special
                treatment of the case where the list has exactly one element.

                I.e. instead of [[1,2,], 3, [5,6,]] maybe you really want
                [[1,2,], [3,], [5,6]] without the special treatment and flattening.


                Comment

                • James Stroud

                  #9
                  Re: Flatten a list/tuple and Call a function with tuples

                  beginner wrote:
                  On Jul 25, 10:19 am, Stargaming <stargam...@gma il.comwrote:
                  >On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
                  >>Hi,
                  >>I am wondering how do I 'flatten' a list or a tuple? For example, I'd
                  >>like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
                  >A recursive function, always yielding the first element of the list,
                  >could do the job. See the ASPN Python Cookbook for a few implementations .http://aspn.activestate.com/ASPN/search?
                  >query=flatten& section=PYTHONC KBK&type=Subsec tion
                  >>
                  >>Another question is how do I pass a tuple or list of all the aurgements
                  >>of a function to the function. For example, I have all the arguments of
                  >>a function in a tuple a=(1,2,3). Then I want to pass each item in the
                  >>tuple to a function f so that I make a function call f(1,2,3). In perl
                  >>it is a given, but in python, I haven't figured out a way to do it.
                  >>(Maybe apply? but it is deprecated?)
                  >>>>def foo(a, b, c): print a, b, c
                  >...
                  >>>>t = (1, 2, 3)
                  >>>>foo(*t)
                  >1 2 3
                  >>
                  >Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
                  >current/tut/node6.html#SECT ION006740000000 000000000
                  >>
                  >>Thanks,
                  >>cg
                  >HTH,
                  >Stargaming
                  >
                  Hi Stargaming,
                  >
                  I know the * operator. However, a 'partial unpack' does not seem to
                  work.
                  >
                  def g():
                  return (1,2)
                  >
                  def f(a,b,c):
                  return a+b+c
                  >
                  f(*g(),10) will return an error.
                  >
                  Do you know how to get that to work?
                  >
                  Thanks,
                  cg
                  >
                  >
                  Were this not hypothetical, I would make use of the commutative property
                  of addition:

                  f(10, *g())

                  Proof:

                  1+2+10 = 10+1+2


                  Also, this has not been suggested:

                  pydef g():
                  .... return (1,2)
                  ....
                  pydef f(a,b,c):
                  .... return a+b+c
                  ....
                  pyf(c=10, *g())
                  13


                  James

                  Comment

                  • Wildemar Wildenburger

                    #10
                    Re: Flatten a list/tuple and Call a function with tuples

                    kyosohma@gmail. com wrote:
                    On Jul 25, 9:50 am, beginner <zyzhu2...@gmai l.comwrote:
                    >
                    >Another question is how do I pass a tuple or list of all the
                    >aurgements of a function to the function. For example, I have all the
                    >arguments of a function in a tuple a=(1,2,3). Then I want to pass each
                    >item in the tuple to a function f so that I make a function call
                    >f(1,2,3). In perl it is a given, but in python, I haven't figured out
                    >a way to do it. (Maybe apply? but it is deprecated?)
                    >>
                    I'm not sure about the first question, but as for the second, you
                    could do a few different things. You could just pass the tuple itself
                    into the function and have the tuple unpacked inside the function.
                    >
                    OR you could use the syntax invented for just that purpose ;).
                    >>t = 1, 2, 3
                    >>f(*t)
                    bam! :)

                    This works with dicts as well (for giving keyword arguments). There you
                    prepend ** (two asterisk to your dict).
                    Simple :)
                    /W

                    Comment

                    • attn.steven.kuo@gmail.com

                      #11
                      Re: Flatten a list/tuple and Call a function with tuples

                      On Jul 25, 8:46 am, beginner <zyzhu2...@gmai l.comwrote:
                      On Jul 25, 10:19 am, Stargaming <stargam...@gma il.comwrote:
                      >
                      >
                      >
                      On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
                      Hi,
                      >
                      I am wondering how do I 'flatten' a list or a tuple? For example, I'd
                      like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
                      >
                      A recursive function, always yielding the first element of the list,
                      could do the job. See the ASPN Python Cookbook for a few implementations .http://aspn.activestate.com/ASPN/search?
                      query=flatten&s ection=PYTHONCK BK&type=Subsect ion
                      >
                      Another question is how do I pass a tuple or list of all the aurgements
                      of a function to the function. For example, I have all the arguments of
                      a function in a tuple a=(1,2,3). Then I want to pass each item in the
                      tuple to a function f so that I make a function call f(1,2,3). In perl
                      it is a given, but in python, I haven't figured out a way to do it.
                      (Maybe apply? but it is deprecated?)
                      >>def foo(a, b, c): print a, b, c
                      ...
                      >>t = (1, 2, 3)
                      >>foo(*t)
                      >
                      1 2 3
                      >
                      Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
                      current/tut/node6.html#SECT ION006740000000 000000000
                      >
                      Thanks,
                      cg
                      >
                      HTH,
                      Stargaming
                      >
                      Hi Stargaming,
                      >
                      I know the * operator. However, a 'partial unpack' does not seem to
                      work.
                      >
                      def g():
                      return (1,2)
                      >
                      def f(a,b,c):
                      return a+b+c
                      >
                      f(*g(),10) will return an error.
                      >
                      Do you know how to get that to work?


                      You can use the "partial" method from functools:

                      import functools

                      sum_of_three = functools.parti al(f, *g())(10)


                      --
                      Hope this helps,
                      Steven


                      Comment

                      • George Sakkis

                        #12
                        Re: Flatten a list/tuple and Call a function with tuples

                        On Jul 25, 12:00 pm, kyoso...@gmail. com wrote:
                        On Jul 25, 10:46 am, beginner <zyzhu2...@gmai l.comwrote:
                        >
                        >
                        >
                        On Jul 25, 10:19 am, Stargaming <stargam...@gma il.comwrote:
                        >
                        On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
                        Hi,
                        >
                        I am wondering how do I 'flatten' a list or a tuple? For example, I'd
                        like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4].
                        >
                        A recursive function, always yielding the first element of the list,
                        could do the job. See the ASPN Python Cookbook for a few implementations .http://aspn.activestate.com/ASPN/search?
                        query=flatten&s ection=PYTHONCK BK&type=Subsect ion
                        >
                        Another question is how do I pass a tuple or list of all the aurgements
                        of a function to the function. For example, I have all the arguments of
                        a function in a tuple a=(1,2,3). Then I want to pass each item in the
                        tuple to a function f so that I make a function call f(1,2,3). In perl
                        it is a given, but in python, I haven't figured out a way to do it.
                        (Maybe apply? but it is deprecated?)
                        >def foo(a, b, c): print a, b, c
                        ...
                        >t = (1, 2, 3)
                        >foo(*t)
                        >
                        1 2 3
                        >
                        Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
                        current/tut/node6.html#SECT ION006740000000 000000000
                        >
                        Thanks,
                        cg
                        >
                        HTH,
                        Stargaming
                        >
                        Hi Stargaming,
                        >
                        I know the * operator. However, a 'partial unpack' does not seem to
                        work.
                        >
                        def g():
                        return (1,2)
                        >
                        def f(a,b,c):
                        return a+b+c
                        >
                        f(*g(),10) will return an error.
                        >
                        Do you know how to get that to work?
                        >
                        Thanks,
                        cg
                        >
                        As I mentioned, you can access the elements individually using square
                        brackets. The following works:
                        >
                        f(g()[0], g()[1], 10)
                        >
                        But it's not clear. Unfortunately, I'm not seeing much else for tuple
                        unpacking except the obvious:
                        >
                        a,b=g()
                        f(a,b,10)
                        >
                        Mike
                        Or if you'd rather write it in one line:

                        f(*(g() + (10,)))

                        George

                        Comment

                        • Jeff

                          #13
                          Re: Flatten a list/tuple and Call a function with tuples

                          Here's a quick flatten() function:

                          def flatten(obj):
                          if type(obj) not in (list, tuple, str):
                          raise TypeError("Stri ng, list, or tuple expected in
                          flatten().")
                          if len(obj) == 1:
                          if type(obj[0]) in (tuple, list):
                          return flatten(obj[0])
                          else:
                          return [obj[0]]
                          else:
                          return [obj[0]] + flatten(obj[1:])

                          x = [1, 2, (3, 4)]
                          y = (1, 2, [3, 4])
                          z = "It even works with strings!"
                          d = {"foo": "bar", "baz": "bat"}

                          print flatten(x)
                          print flatten(y)
                          print flatten(z)
                          print flatten(d)

                          Comment

                          • Aneesh Goel

                            #14
                            Re: Flatten a list/tuple and Call a function with tuples

                            On Jul 25, 10:33 am, Jeff <jeffo...@gmail .comwrote:
                            def flatten(obj):
                            if type(obj) not in (list, tuple, str):
                            raise TypeError("Stri ng, list, or tuple expected in
                            flatten().")
                            if len(obj) == 1:
                            if type(obj[0]) in (tuple, list):
                            return flatten(obj[0])
                            else:
                            return [obj[0]]
                            else:
                            return [obj[0]] + flatten(obj[1:])
                            This seems to work fine only if the last object is the only one with
                            the tuple or list. For example:
                            >>y = [(1,2),3,4]
                            >>y
                            [(1, 2), 3, 4]
                            >>print flatten(y)
                            [(1, 2), 3, 4]

                            if the last line is changed to

                            return flatten([obj[0]]) + flatten(obj[1:])

                            then it will unpack tuples/lists anywhere in the main collection being
                            flattened:
                            >>y
                            [(1, 2), 3, 4]
                            >>flatten(y)
                            [1, 2, 3, 4]
                            >>z = [1,(2,3),4]
                            >>flatten(z)
                            [1, 2, 3, 4]
                            >>x
                            [1, 2, (3, 4)]
                            >>flatten(x)
                            [1, 2, 3, 4]
                            >>k = [(1,2),(3,4)]
                            >>flatten(k)
                            [1, 2, 3, 4]

                            Comment

                            • Neil Cerutti

                              #15
                              Re: Flatten a list/tuple and Call a function with tuples

                              On 2007-07-25, Jeff <jeffober@gmail .comwrote:
                              Here's a quick flatten() function:
                              >
                              def flatten(obj):
                              if type(obj) not in (list, tuple, str):
                              raise TypeError("Stri ng, list, or tuple expected in
                              flatten().")
                              if len(obj) == 1:
                              if type(obj[0]) in (tuple, list):
                              return flatten(obj[0])
                              else:
                              return [obj[0]]
                              else:
                              return [obj[0]] + flatten(obj[1:])
                              >
                              x = [1, 2, (3, 4)]
                              y = (1, 2, [3, 4])
                              z = "It even works with strings!"
                              d = {"foo": "bar", "baz": "bat"}
                              e = [[1], 2, 3, , 4]
                              f = [1, 2, 3, 4, []]

                              --
                              Neil Cerutti

                              Comment

                              Working...