Search code examples
pythontuplesreadability

Tuples readability : [0,0] vs (0,0)


I'm using Python since some times and I am discovering the "pythonic" way to code. I am using a lot of tuples in my code, most of them are polar or Cartesian positions.

I found myself writing this :

window.set_pos([18,8])

instead of this :

window.set_pos((18,8))

to get rid of the double parenthesis I found hard to read.

It seems that python is automatically doing the type conversion from list to tuple, as my code works properly.

But is it a good way to code ? Do you have any presentation tip I could use to write readable code ?

Thank you in advance for your surely enlightening answers.


Solution

  • I'd be careful deciding to eschew tuples in favor of lists everywhere. Have you ever used the dis module? Watch what Python is doing at the bytecode level when you make a list verses making a tuple:

    >>> def f():
    ...     x = [1,2,3,4,5,6,7]
    ...     return x
    ... 
    >>> def g():
    ...     x = (1,2,3,4,5,6,7)
    ...     return x
    ... 
    >>> import dis
    >>> dis.dis(f)
      2           0 LOAD_CONST               1 (1)
                  3 LOAD_CONST               2 (2)
                  6 LOAD_CONST               3 (3)
                  9 LOAD_CONST               4 (4)
                 12 LOAD_CONST               5 (5)
                 15 LOAD_CONST               6 (6)
                 18 LOAD_CONST               7 (7)
                 21 BUILD_LIST               7
                 24 STORE_FAST               0 (x)
    
      3          27 LOAD_FAST                0 (x)
                 30 RETURN_VALUE     
    >>>
    >>>   
    >>> dis.dis(g)
      2           0 LOAD_CONST               8 ((1, 2, 3, 4, 5, 6, 7))
                  3 STORE_FAST               0 (x)
    
      3           6 LOAD_FAST                0 (x)
                  9 RETURN_VALUE   
    

    Though it will probably never be an issue in a GUI application (as your example seems to be), for performance reasons you may want to be careful about doing it everywhere in your code.