title: CPython: Is there any way to traverse a PyObject as a sequence without having to create and destroy objects subsequently?
body: <p>To make a PyObject that acts as a sequence, I just added a fuction to the slot <code>sq_item</code> of the variable <code>tp_as_sequence</code> of a <code>PyTypeObject</code>.</p>
  
  <p>Here is my <code>sq_item</code> function:</p>
  
  <pre><code>static PyObject *py_myseq__sq_item(PyMySeq *self, unsigned int keynum)
  {
      if (keynum &lt; 0) keynum += self-&gt;len; /* ex.:&gt;&gt;&gt; my_seq[-1] */
      if (keynum &gt;= 0 &amp;&amp; keynum &lt; self-&gt;len) {
          MyItem *item = &amp;self-&gt;items[keynum];
  
          return PyMyItem_New(item);
      }
  
      PyErr_Format(PyExc_IndexError,
                   "PyMySeq[index]: index %d out of range", keynum);
      return NULL;
  }
  </code></pre>
  
  <p>Every time I want to get a item of the sequence, the <code>PyMyItem_New</code> function is called. This is good in most cases. But to cases like when using a for loop this is quite inefficient:</p>
  
  <pre><code>for i in myPyObjSeq:
      print(i)
  </code></pre>
  
  <p>If my sequence has one million items. The items will be created and destroyed 1 million times in this loop!!!</p>
  
  <p>The question is: Is there any way to avoid this???</p>