title: How to arrange an existing Python list of integers consecutively in memory?
body: <p>The following blog post shows that a list of integers is processed quicker if the list is not randomly shuffled. Due to cache locality, the unshuffled list is faster to process since its adjacent elements are located adjacently in memory.</p>
  
  <p><a href="https://rickystewart.wordpress.com/2013/09/03/why-sorting-an-array-makes-a-python-loop-faster/" rel="nofollow noreferrer">https://rickystewart.wordpress.com/2013/09/03/why-sorting-an-array-makes-a-python-loop-faster/</a></p>
  
  <p>I tried the following approach so that the shuffled list would be re-ordered with adjacent elements consecutive in memory.</p>
  
  <pre><code>import copy
  a = [i for i in range(1000000)]
  shuffle(a)
  # Approach 1
  a = copy.deepcopy(a)
  </code></pre>
  
  <p>However, that did not improve performance, suggesting that the items aren't reordered consecutively in memory.</p>
  
  <p>I also tried the following modifications after shuffling, which also did not improve performance.</p>
  
  <pre><code># Approach 2
  a = [x for x in a]
  
  # Approach 3
  a = [copy.deepcopy(x) for x in a]
  </code></pre>
  
  <p>The following approach improves performance, suggesting that the elements are re-ordered in memory.</p>
  
  <pre><code># Approach 4
  a = [x+0 for x in a]
  </code></pre>
  
  <p>My question is why do approaches 1 through 3 not re-order the elements in memory, whereas approach 4 does?</p>
  
  <p>Is there a suggested way to do this, different from approach 4?</p>