But now I have absolutely no idea where I’m supposed to go after this. I can sort of see that I need to print in slices of 2 letters, starting with aa ab bb etc but have no idea how to do it. I’ve been staring at the screen for about an hour now and have given up.
I can think of at least a couple of different interpretations for this. Can you clarify your exact requirements? Assuming you need to select all the pairs and not just adjacent pairs, are “ad” and “da” equivalent for this task, or distinct? (i.e. are you looking for combinations, or permutations?) Are you supposed to do this “by hand” or is it allowed to utilized stdlib modules like itertools?
That works fine but is a bit beyond my skill level. There’s no way I would have known that. Maybe I should look for some beginner books before jumping in too far.
You’re welcome. The book that I use that is pretty comprehensive and pretty much covers it all is Learning Python, 5th Edition. It does require a lot of effort, however. I am learning Python myself actually. I would strongly recommend it as it is very much like taking a course in Python.
for is just an iterator, meaning it steps through a series of items one at a time.
In the code, letters is a series of things. So, the first for loop gets a handle of one letter, then it proceeds to the next for iterator, where it iterates through the entire list of letters. Once having done so, it continues to the letter b. It then repeats this process for the remaining letters.
Based on the description, the thing being sought is what is called a “Cartesian product”. A nested loop is definitely a straightforward way of enumerating all the items in a basic Cartesian product. But also just for your future reference, know that optimized or generalized versions of things like this may also be built in to the standard library. For instance in this case there is itertools.product available that can compute N-way products of any set with itself:
from string import ascii_lowercase
from itertools import product
for a, b in product(ascii_lowercase, repeat=2):
print(f"{a}{b}")
I wonder which solution is faster. Probably your f-string is faster but your iteration is slower (and I find it a bit misleading to mention “optimized” there). And I wonder about the simple print(a + b) as well…