How to make all possible combinations of a word in Python
<p>I have a txt file with all of the letters in the alphabet that looks like this:</p>

<p>a</p>

<p>b</p>

<p>c</p>

<p>etc..</p>

<p>I also have a word list of words that is only 3 letters long:</p>

<p>ago</p>

<p>age</p>

<p>bat</p>

<p>bag</p>

<p>etc...</p>

<p>I want to create a list that prints out all of the combinations possible starting with the first word ago:</p>

<p>My test program looks like this:</p>

<pre><code>allcombi=[]
s= list("ago")
the.list=[]
with open("alfabeth.txt", "r", encoding = "utf-8") as letters:
    for line in letters:
        letter = line.strip()
        s[0]=letter
        print(s)
</code></pre>

<p>Now I only change the first letter, but I have a really hard time trying to join the letters because it only looks like this:</p>

<p>['a', 'g', 'o']
['b', 'g', 'o']
....</p>

<p>HELP WITH:</p>

<ol>
<li><p>Print it out as  ['ago','bgo'] instead</p></li>
<li><p>Instead of just changing the first letter, change it one letter at a time in index 0,1 and 2 one letter at a time in the word. The output should be 27*3 rows long with ['ago','bgo',........,'agx',agy,'agz']   </p></li>
</ol>

<p>I will later search for all of the items in my new list in a dictionary but that I can figure out myself it's just this part that really gotten me stuck.</p>

<p>You need a few nested loops to get the combinations, as an example:</p>

<pre class="lang-python prettyprint-override"><code>from string import ascii_lowercase

words = ["ago"]
combs = []
for word in words:
    for i, letter in enumerate(word):
        for l in ascii_lowercase:
            tmp = list(word)
            tmp[i] = l
            combs.append("".join(tmp))

print combs



&gt;&gt;&gt; ['ago', 'bgo', 'cgo', 'dgo', 'ego', 'fgo', 'ggo', 'hgo', 'igo', 'jgo', 'kgo', 'lgo', 'mgo', 'ngo', 'ogo', 'pgo', 'qgo', 'rgo', 'sgo', 'tgo', 'ugo', 'vgo', 'wgo', 'xgo', 'ygo', 'zgo', 'aao', 'abo', 'aco', 'ado', 'aeo', 'afo', 'ago', 'aho', 'aio', 'ajo', 'ako', 'alo', 'amo', 'ano', 'aoo', 'apo', 'aqo', 'aro', 'aso', 'ato', 'auo', 'avo', 'awo', 'axo', 'ayo', 'azo', 'aga', 'agb', 'agc', 'agd', 'age', 'agf', 'agg', 'agh', 'agi', 'agj', 'agk', 'agl', 'agm', 'agn', 'ago', 'agp', 'agq', 'agr', 'ags', 'agt', 'agu', 'agv', 'agw', 'agx', 'agy', 'agz']
</code></pre>

python string list replace letter