Lists and Tuples

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

    Lists and Tuples

    I've spent most of the day playing around with lists and tuples to get a really good grasp on what
    you can do with them. I am still left with a question and that is, when should you choose a list or
    a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it
    than just that. Everything I tried with a list worked the same with a tuple. So, what's the
    difference and why choose one over the other?

    Jeff
  • Paul Rubin

    #2
    Re: Lists and Tuples

    Jeff Wagner <JWagner@hotmai l.com> writes:[color=blue]
    > I've spent most of the day playing around with lists and tuples to
    > get a really good grasp on what you can do with them. I am still
    > left with a question and that is, when should you choose a list or a
    > tuple? I understand that a tuple is immutable and a list is mutable
    > but there has to be more to it than just that. Everything I tried
    > with a list worked the same with a tuple. So, what's the difference
    > and why choose one over the other?[/color]


    Try this with a list:

    a = [1, 2, 3, 4, 5]
    a[3] = 27
    print a

    Then try it with a tuple.

    Comment

    • David Eppstein

      #3
      Re: Lists and Tuples

      In article <7x7k1b4yqn.fsf @ruckus.brouhah a.com>,
      Paul Rubin <http://phr.cx@NOSPAM.i nvalid> wrote:
      [color=blue]
      > Try this with a list:
      >
      > a = [1, 2, 3, 4, 5]
      > a[3] = 27
      > print a
      >
      > Then try it with a tuple.[/color]

      That's true, but another answer is: you should use tuples for short
      sequences of diverse items (like the arguments to a function). You
      should use lists for longer sequences of similar items.

      --
      David Eppstein http://www.ics.uci.edu/~eppstein/
      Univ. of California, Irvine, School of Information & Computer Science

      Comment

      • Jeff Wagner

        #4
        Re: Lists and Tuples

        On 04 Dec 2003 21:31:12 -0800, Paul Rubin <http://phr.cx@NOSPAM.i nvalid> wrotf:
        [color=blue]
        >Jeff Wagner <JWagner@hotmai l.com> writes:[color=green]
        >> I've spent most of the day playing around with lists and tuples to
        >> get a really good grasp on what you can do with them. I am still
        >> left with a question and that is, when should you choose a list or a
        >> tuple? I understand that a tuple is immutable and a list is mutable
        >> but there has to be more to it than just that. Everything I tried
        >> with a list worked the same with a tuple. So, what's the difference
        >> and why choose one over the other?[/color]
        >
        >
        >Try this with a list:
        >
        > a = [1, 2, 3, 4, 5]
        > a[3] = 27
        > print a
        >
        >Then try it with a tuple.[/color]

        That's because a tuple is immutable and a list is mutable but what else? I guess I said everything I
        tried with a tuple worked with a list ... not mentioning I didn't try to break the immutable/mutable
        rule I was aware of. Besides trying to change a tuple, I could cut it, slice and dice it just like I
        could a list. They seemed to have the same built-in methods, too.

        From what I can see, there is no reason for me to ever want to use a tuple and I think there is
        something I am missing. Why would Guido go to all the effort to include tuples if (as it appears)
        lists are just as good but more powerful ... you can change the contents of a list.

        Jeff

        Comment

        • Andrew Bennetts

          #5
          Re: Lists and Tuples

          On Fri, Dec 05, 2003 at 05:19:33AM +0000, Jeff Wagner wrote:[color=blue]
          > I've spent most of the day playing around with lists and tuples to get a really good grasp on what
          > you can do with them. I am still left with a question and that is, when should you choose a list or
          > a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it
          > than just that. Everything I tried with a list worked the same with a tuple. So, what's the
          > difference and why choose one over the other?[/color]

          What's the difference?
          [color=blue][color=green][color=darkred]
          >>> import sets
          >>> sets.Set(dir(li st)).difference (sets.Set(dir(t uple)))[/color][/color][/color]
          Set(['sort', 'index', '__delslice__', 'reverse', 'extend', 'insert',
          '__setslice__', 'count', 'remove', '__setitem__', '__iadd__', 'pop',
          '__delitem__', 'append', '__imul__'])

          ;)

          -Andrew.


          Comment

          • sdd

            #6
            Re: Lists and Tuples

            Jeff Wagner wrote:[color=blue]
            > I've spent most of the day playing around with lists and tuples to get a really good grasp on what
            > you can do with them. I am still left with a question and that is, when should you choose a list or
            > a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it
            > than just that. Everything I tried with a list worked the same with a tuple. So, what's the
            > difference and why choose one over the other?
            >
            > Jeff[/color]
            Here's the biggie:

            association = {}
            somevals = 1,2,6,'a'
            association[somevals] = 13

            vs.

            association = {}
            somevals = [1,2,6,'a']
            association[somevals] = 13

            -Scott David Daniels
            Scott.Daniels@A cm.Org

            Comment

            • Dennis Lee Bieber

              #7
              Re: Lists and Tuples

              Jeff Wagner fed this fish to the penguins on Thursday 04 December 2003
              21:19 pm:
              [color=blue]
              > tuple. So, what's the difference and why choose one over the other?
              >[/color]
              A tuple can be the key for a dictionary, a list can't.


              Not sure of a tuple containing a list, though...

              --[color=blue]
              > =============== =============== =============== =============== == <
              > wlfraed@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
              > wulfraed@dm.net | Bestiaria Support Staff <
              > =============== =============== =============== =============== == <
              > Bestiaria Home Page: http://www.beastie.dm.net/ <
              > Home Page: http://www.dm.net/~wulfraed/ <[/color]

              Comment

              • Douglas Alan

                #8
                Re: Lists and Tuples

                David Eppstein <eppstein@ics.u ci.edu> writes:
                [color=blue]
                > That's true, but another answer is: you should use tuples for short
                > sequences of diverse items (like the arguments to a function). You
                > should use lists for longer sequences of similar items.[/color]

                I disagree. You should use a tuple when you wish to not change the
                contents once you have constructed the sequence, and otherwise you
                should use a list. Using a tuple can make your code clearer by
                letting the reader know from the beginning that the contents won't be
                changing.

                Fredrik Lundh actually called me names a couple years back for
                asserting this, but Python luminary (and rude fellow) or not, he is
                dead wrong.

                You don't have to take my word for it, though, since Python itself
                uses tuples in this manner, in the form of the container used for
                excess arguments (excess arguments certainly don't have to be short,
                and they are generally homogeneous, not heterogeneous), and Python
                Mega Widgets (for example) is littered with code that looks like:

                optiondefs = (
                ('initwait', 500, None), # milliseconds
                ('label_backgro und', 'lightyellow', None),
                ('label_foregro und', 'black', None),
                ('label_justify ', 'left', None),
                ('master', 'parent', None),
                ('relmouse', 'none', self._relmouse) ,
                ('state', 'both', self._state),
                ('statuscommand ', None, None),
                ('xoffset', 20, None), # pixels
                ('yoffset', 1, None), # pixels
                ('hull_highligh tthickness', 1, None),
                ('hull_highligh tbackground', 'black', None),
                )

                In the above case we see tuples being used both as records *and* as an
                arbitrary-length sequence of homogenious elements. Why is a tuple
                being used in the latter case, rather than a list? Because the
                sequence isn't going to be modified.

                |>oug

                Comment

                • Bengt Richter

                  #9
                  Re: Lists and Tuples

                  On Thu, 04 Dec 2003 21:45:23 -0800, David Eppstein <eppstein@ics.u ci.edu> wrote:
                  [color=blue]
                  >In article <7x7k1b4yqn.fsf @ruckus.brouhah a.com>,
                  > Paul Rubin <http://phr.cx@NOSPAM.i nvalid> wrote:
                  >[color=green]
                  >> Try this with a list:
                  >>
                  >> a = [1, 2, 3, 4, 5]
                  >> a[3] = 27
                  >> print a
                  >>
                  >> Then try it with a tuple.[/color]
                  >
                  >That's true, but another answer is: you should use tuples for short
                  >sequences of diverse items (like the arguments to a function). You
                  >should use lists for longer sequences of similar items.
                  >[/color]
                  I'm curious what you're getting at. I.e., what does diversity or
                  similarity have to do with the choice? Is that an aesthetic thing?
                  (In which case 'should' should be qualified a bit, IWT ;-)
                  Or what am I missing?

                  Regards,
                  Bengt Richter

                  Comment

                  • Douglas Alan

                    #10
                    Re: Lists and Tuples

                    X-Draft-From: ("comp.lang.pyt hon" 285349)
                    To: bokr@oz.net (Bengt Richter)
                    Subject: Re: Lists and Tuples
                    References: <r650tv4f9b2k96 7jgc0cta3vllfoh b49il@4ax.com>
                    <7x7k1b4yqn.fsf @ruckus.brouhah a.com>
                    <eppstein-039667.21452204 122003@news.ser vice.uci.edu>
                    <bqpfde$426$0@2 16.39.172.122>
                    Fcc: |rcvstore +articles
                    From: Douglas Alan <nessus@mit.edu >
                    --text follows this line--
                    bokr@oz.net (Bengt Richter) writes:
                    [color=blue]
                    > On Thu, 04 Dec 2003 21:45:23 -0800, David Eppstein
                    > <eppstein@ics.u ci.edu> wrote:[/color]
                    [color=blue][color=green]
                    >> That's true, but another answer is: you should use tuples for short
                    >> sequences of diverse items (like the arguments to a function). You
                    >> should use lists for longer sequences of similar items.[/color][/color]
                    [color=blue]
                    > I'm curious what you're getting at. I.e., what does diversity or
                    > similarity have to do with the choice?[/color]

                    Nothing really, except by idiom. When people use "should" here, I
                    think they are over-generalizing. Most of the time, records (short
                    and heterogenious) are used in a read-only fashion, and long
                    homogenous sequences are used in a read-write fashion. But when
                    people characterize this tendency with a "should", I think they are
                    making a thinko. There are times when you need to modify a record and
                    consequently might use a dictionary or list, rather than a tuple,
                    and there are also times when you will never want to modify a long,
                    homogenous sequence, in which case many people would find it more
                    elegant to use a tuple than to use a list.

                    The reason for the "should" is probably because, I imagine, Guido had
                    in mind mostly multiple return values from function, and the like,
                    when he put tuples into the language.

                    |>oug

                    Comment

                    • Joe Francia

                      #11
                      Re: Lists and Tuples

                      Jeff Wagner wrote:[color=blue]
                      > I've spent most of the day playing around with lists and tuples to get a really good grasp on what
                      > you can do with them. I am still left with a question and that is, when should you choose a list or
                      > a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it
                      > than just that. Everything I tried with a list worked the same with a tuple. So, what's the
                      > difference and why choose one over the other?
                      >[/color]

                      According to the Python FAQ:

                      ------------------------------------------------------------------------
                      4.15 Why are there separate tuple and list data types?

                      Lists and tuples, while similar in many respects, are generally used in
                      fundamentally different ways. Tuples can be thought of as being similar
                      to Pascal records or C structs; they're small collections of related
                      data which may be of different types which are operated on as a group.
                      For example, a Cartesian coordinate is appropriately represented as a
                      tuple of two or three numbers.

                      Lists, on the other hand, are more like arrays in other languages. They
                      tend to hold a varying number of objects all of which have the same type
                      and which are operated on one-by-one. For example, os.listdir('.')
                      returns a list of strings representing the files in the current
                      directory. Functions which operate on this output would generally not
                      break if you added another file or two to the directory.

                      Tuples are immutable, meaning that once a tuple has been created, you
                      can't replace any of its elements with a new value. Lists are mutable,
                      meaning that you can always change a list's elements. Only immutable
                      elements can be used as dictionary keys, and hence only tuples and not
                      lists can be used as keys.


                      ------------------------------------------------------------------------

                      Of course, this information will prevent neither flame wars, nor you
                      from using them how you wish (within the boundaries of the language).
                      However you choose to use them, just be clear and consistent.

                      Peace,
                      Joe

                      Comment

                      • Duncan Booth

                        #12
                        Re: Lists and Tuples

                        Jeff Wagner <JWagner@hotmai l.com> wrote in
                        news:f570tv43pa 27td77188ljkk87 vl19gif6p@4ax.c om:
                        [color=blue]
                        > From what I can see, there is no reason for me to ever want to use a
                        > tuple and I think there is something I am missing. Why would Guido go
                        > to all the effort to include tuples if (as it appears) lists are just
                        > as good but more powerful ... you can change the contents of a list.[/color]

                        The most practical difference (if you don't need to modify the contents) is
                        that tuples can be used as dictionary keys, but lists cannot. There is a
                        minor performance difference, in particular tuples will take less memory so
                        if you have a few million of them kicking around your application you might
                        notice the difference.

                        However, as other posters have suggested the best way to look at it is
                        often to use tuples when you have a fixed number of objects, possibly of
                        different types, e.g. a database record. When you have a variable number of
                        objects (usually of the same type, or supporting a similar interface) then
                        a list if obviously better. If you have a variable number of groups of
                        objects, then a list of tuples seems to fit best. In any of these cases you
                        could use a list in place of the tuple, but the distinction can help keep
                        things clear.

                        Bottom line:

                        If you are primarily reading the sequence using constant indices, then use
                        a tuple. If the code starts looking messy then consider defining a class to
                        replace the tuples and using fieldnames instead of constant indices.

                        If you need to use the object as a dictionary key, or if you have reason to
                        be concerned about memory use (because there are a lot of them) use a
                        tuple.

                        Otherwise use a list.

                        --
                        Duncan Booth duncan@rcp.co.u k
                        int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
                        "\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?

                        Comment

                        • Fredrik Lundh

                          #13
                          Re: Lists and Tuples

                          Douglas Alan wrote:
                          [color=blue]
                          > I disagree. You should use a tuple when you wish to not change the
                          > contents once you have constructed the sequence, and otherwise you
                          > should use a list.[/color]
                          [color=blue]
                          > Fredrik Lundh actually called me names a couple years back for
                          > asserting this, but Python luminary (and rude fellow) or not, he is
                          > dead wrong.[/color]

                          I'm never dead wrong.

                          Guido van Rossum, "State of the Python Union", March 2003:


                          ...

                          + It's a matter of user education

                          + Example: lists vs. tuples

                          this is often misrepresented as "tuple are readonly lists",
                          which is *wrong*

                          use cases are quite different

                          *but*... tuples also usable as readonly lists

                          ...

                          I expect an apology.

                          </F>




                          Comment

                          • Michael Hudson

                            #14
                            Re: Lists and Tuples

                            Dennis Lee Bieber <wlfraed@ix.net com.com> writes:
                            [color=blue]
                            > Jeff Wagner fed this fish to the penguins on Thursday 04 December 2003
                            > 21:19 pm:
                            >[color=green]
                            > > tuple. So, what's the difference and why choose one over the other?
                            > >[/color]
                            > A tuple can be the key for a dictionary, a list can't.
                            >
                            >
                            > Not sure of a tuple containing a list, though...[/color]

                            Nope. A tuple is hashable iff all of its elements are.

                            Cheers,
                            mwh

                            --
                            Now this is what I don't get. Nobody said absolutely anything
                            bad about anything. Yet it is always possible to just pull
                            random flames out of ones ass.
                            -- http://www.advogato.org/person/vicio....html?start=60

                            Comment

                            • Dang Griffith

                              #15
                              Re: Lists and Tuples

                              On Fri, 5 Dec 2003 16:59:57 +1100, Andrew Bennetts
                              <andrew-pythonlist@puzz ling.org> wrote:
                              [color=blue]
                              >On Fri, Dec 05, 2003 at 05:19:33AM +0000, Jeff Wagner wrote:[color=green]
                              >> I've spent most of the day playing around with lists and tuples to get a really good grasp on what
                              >> you can do with them. I am still left with a question and that is, when should you choose a list or
                              >> a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it
                              >> than just that. Everything I tried with a list worked the same with a tuple. So, what's the
                              >> difference and why choose one over the other?[/color]
                              >
                              >What's the difference?
                              >[color=green][color=darkred]
                              >>>> import sets
                              >>>> sets.Set(dir(li st)).difference (sets.Set(dir(t uple)))[/color][/color]
                              >Set(['sort', 'index', '__delslice__', 'reverse', 'extend', 'insert',
                              >'__setslice__' , 'count', 'remove', '__setitem__', '__iadd__', 'pop',
                              >'__delitem__ ', 'append', '__imul__'])
                              >
                              >;)
                              >
                              >-Andrew.
                              >[/color]
                              I like that--ask a simple question, get a simple answer. Why can't
                              they all be so straightforward . :-)
                              --dang

                              Comment

                              Working...