Ad hoc lists vs ad hoc tuples

Discussion in 'Python' started by Floris Bruynooghe, Jan 27, 2010.

  1. One thing I ofter wonder is which is better when you just need a
    throwaway sequence: a list or a tuple? E.g.:

    if foo in ['some', 'random', 'strings']:
    ...
    if [bool1, bool2, boo3].count(True) != 1:
    ...

    (The last one only works with tuples since python 2.6)

    Is a list or tuple better or more efficient in these situations?


    Regards
    Floris

    PS: This is inspired by some of the space-efficiency comments from the
    list.pop(0) discussion.
     
    Floris Bruynooghe, Jan 27, 2010
    #1
    1. Advertisements

  2. Floris Bruynooghe

    Iain King Guest

    I tend to use tuples unless using a list makes it easier to read. For
    example:

    if foo in ('some', 'random', 'strings'):

    draw.text((10,30), "WHICH IS WHITE", font=font)
    draw.line([(70,25), (85,25), (105,45)])

    I've no idea what the performance difference is; I've always assumed
    it's negligible.

    Iain
     
    Iain King, Jan 27, 2010
    #2
    1. Advertisements

  3. Floris Bruynooghe

    Steve Holden Guest

    The fact that you have felt able to neglect the performance difference
    makes it quite literally negligible.

    regards
    Steve
     
    Steve Holden, Jan 27, 2010
    #3
  4. Floris Bruynooghe

    Steve Holden Guest

    The fact that you have felt able to neglect the performance difference
    makes it quite literally negligible.

    regards
    Steve
     
    Steve Holden, Jan 27, 2010
    #4
  5. Le Wed, 27 Jan 2010 02:20:53 -0800, Floris Bruynooghe a écrit :
    Tuples are faster to allocate (they are allocated in one single step) and
    quite a bit smaller too.
    In some situations, in Python 2.7 and 3.1, they can also be ignored by
    the garbage collector, yielding faster collections.

    (not to mention that they are hashable, which can be useful)
     
    Antoine Pitrou, Jan 27, 2010
    #5
  6. Floris Bruynooghe

    Terry Reedy Guest

    Constant tuples (a tuple whose members are all seen as constants by the
    compiler) are now pre-compiled and constructed once and put into the
    code object as such rather than re-constructed with each run of the code.
    1 0 LOAD_CONST 1 (1)
    3 LOAD_CONST 2 (2)
    6 LOAD_CONST 3 (3)
    9 BUILD_LIST 3
    12 RETURN_VALUE 1 0 LOAD_CONST 4 ((1, 2, 3))
    3 RETURN_VALUE
    Terry Jan Reedy
     
    Terry Reedy, Jan 27, 2010
    #6
  7. Thanks for all the answers! This is what I was expecting but it's
    nice to see it confirmed.

    Regards
    Floris
     
    Floris Bruynooghe, Jan 28, 2010
    #7
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.