Generating all strings of some length of a given alphabet

This recipe shows a way to generate a list of all strings (in this case, string=list of symbols) of a given alphabet having a specified length; by using list comprehensions.

UPDATE: The case for alphabet length = 1 is fixed.


Strings (not the 'string' type) are frequently used in computer science; for example numbers are encoded as strings of base-2 numbers (having an alphabet of {0,1}). This implementation is just a quick hack; it uses cartesian product to find the stings, so it will consume a large space of memory (m**n lists of size n, where m is the size of the alphabet, and n is the desired length).

For more info. about strings: http://mathworld.wolfram.com/String.html

def allstrings(alphabet, length):
	"""Find the list of all strings of 'alphabet' of length 'length'"""
	
	if length == 0: return []
	
	c = [[a] for a in alphabet[:]]
	if length == 1: return c
	
	c = [[x,y] for x in alphabet for y in alphabet]
	if length == 2: return c
	
	for l in range(2, length):
		c = [[x]+y for x in alphabet for y in c]
		
	return c

if __name__ == "__main__":
	for p in allstrings([0,1,2],4):
		print p

code.activestate.com ↗