Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Absolutely (for the example you provided).</p> <h3>Tuples are first class citizens in Python</h3> <p>There is a builtin function <a href="https://docs.python.org/3/library/functions.html#divmod" rel="nofollow noreferrer"><code>divmod()</code></a> that does exactly that.</p> <pre><code>q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x </code></pre> <p>There are other examples: <code>zip</code>, <code>enumerate</code>, <code>dict.items</code>. </p> <pre><code>for i, e in enumerate([1, 3, 3]): print "index=%d, element=%s" % (i, e) # reverse keys and values in a dictionary d = dict((v, k) for k, v in adict.items()) # or d = dict(zip(adict.values(), adict.keys())) </code></pre> <p>BTW, parentheses are not necessary most of the time. Citation from <a href="https://docs.python.org/3/library/stdtypes.html?highlight=type%20seq#tuple" rel="nofollow noreferrer">Python Library Reference</a>: </p> <blockquote> <p>Tuples may be constructed in a number of ways:</p> <ul> <li>Using a pair of parentheses to denote the empty tuple: ()</li> <li>Using a trailing comma for a singleton tuple: a, or (a,)</li> <li>Separating items with commas: a, b, c or (a, b, c)</li> <li>Using the tuple() built-in: tuple() or tuple(iterable)</li> </ul> </blockquote> <h3>Functions should serve single purpose</h3> <p>Therefore they should return a single object. In your case this object is a tuple. Consider tuple as an ad-hoc compound data structure. There are languages where almost every single function returns multiple values (list in Lisp).</p> <p>Sometimes it is sufficient to return <code>(x, y)</code> instead of <code>Point(x, y)</code>.</p> <h3>Named tuples</h3> <p>With the introduction of named tuples in Python 2.6 it is preferable in many cases to return named tuples instead of plain tuples.</p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; Point = collections.namedtuple('Point', 'x y') &gt;&gt;&gt; x, y = Point(0, 1) &gt;&gt;&gt; p = Point(x, y) &gt;&gt;&gt; x, y, p (0, 1, Point(x=0, y=1)) &gt;&gt;&gt; p.x, p.y, p[0], p[1] (0, 1, 0, 1) &gt;&gt;&gt; for i in p: ... print(i) ... 0 1 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload