title: Can a loop reference a list without naming it, within a global frame?
body: <p>I have been tasked to group a list by frequency.  This is a very common question on SOF and so far the forum has been very educational.  However, of all the examples given, only one follows these perimeters:</p>
  
  <ul>
  <li>Sort the given iterable so that its elements end up in the decreasing frequency order.</li>
  <li>If two elements have the same frequency, they should end up in the same order as the first appearance in the iterable.</li>
  </ul>
  
  <p>Using these two lists:</p>
  
  <pre><code>[4, 6, 2, 2, 6, 4, 4, 4]
  [17, 99, 42]
  </code></pre>
  
  <p>The following common codes given as solutions to this question have failed.</p>
  
  <pre><code>from collections import Counter
  freq = Counter(items)
  
  # Ex 1
  # The items dont stay grouped in the final list :(
  
  sorted(items, key = items.count, reverse=True)
  sorted(items, key=lambda x: -freq[x])
  [4, 4, 4, 4, 6, 2, 2, 6]
  
  
  # Ex 2
  # The order that the items appear in the list gets rearranged :(
  
  sorted(sorted(items), key=freq.get, reverse=True)
  [4, 4, 4, 4, 2, 2, 6, 6]
  
  
  # Ex 3
  # With a list of integers, after the quantity gets sorted, 
  # the int value gets sorted :(
  
  sorted(items, key=lambda x: (freq[x], x), reverse=True)
  [99, 42, 17]
  </code></pre>
  
  <p>I did find a solution that works great though:</p>
  
  <pre><code>s_list = sorted(freq, key=freq.get, reverse=True)
  
  new_list = []
  for num in s_list:
      for rep in range(freq[num]):
          new_list.append(num)
  print(new_list)
  </code></pre>
  
  <p>I can't figure out how the second loop references the number of occurrences though.  </p>
  
  <p>I ran the process through pythontutor to visualize it and the code seems to simply know that there are four "4", two "6" and two "2" in the 'items' list.  The only solution I can think of is that python can reference a list in a global frame without it being named.  Or perhaps being able to utilize the value from the "freq" dictionary.  Is this correct?</p>
  
  <p>referenced thread:
  <a href="https://stackoverflow.com/questions/25815377/sort-list-by-frequency-in-python">Sort list by frequency in python</a></p>