title: optimize a loop that loops over billion times in python
body: <p>i have a list with 170 length.
  and i want to save all of it's 5 length combinations nCr(170, 5) in a file.
  so it's about 1,115,034,284 and i use code below to generate combinations.</p>
  <pre><code>import itertools
  all_texts = [] # my list with length 170
  all_combinations = []
  for subset in itertools.combinations(all_texts, 5):
      text = &quot;&quot;
      for sub in subset:
          text += sub + &quot; &amp;&amp; &quot;
  
      query = text[0:-3]
      all_combinations.append(query)
  
  
  filename = &quot;filename.txt&quot;
  with open(filename, 'w') as f:
      for item in all_combinations:
          f.write(&quot;%s\n&quot; % item)
  </code></pre>
  <p>but this is a huge loop which my server with 128 Gb RAM capacity is unable to do without memory exception error.
  how can i optimize this loop?
  thanks.</p>