>>> [ a[ index : index + length ] for index in range( len( a ) - 1 ) for length in range( 2, len( a ) - index + 1 ) ]
['ab', 'abc', 'abcd', 'bc', 'bcd', 'cd']
If you need the list sorted:
>>> sorted( [ a[ index : index + length ] for index in range( len( a ) - 1 ) for length in range( 2, len( a ) - index + 1 ) ], key = len )
['ab', 'bc', 'cd', 'abc', 'bcd', 'abcd']
There is something seriously wrong with your algorithm, because it should only take two loops to do this (one for starting index and one for length of substring). I don't understand what you were trying to do, though, so I can't attempt to fix it.
EDIT: I get it -- you're copying the strings character by character! Are you a C programmer by any chance? =p You don't have to do that sort of thing in Python; it's a higher-level language. If you slice a string (a[1:3]
) you will get a substring of it, which you can append to a list or otherwise store. In the above, we iterate first over all indices up to the end of the string (minus one because "d" is not a valid substring) and then over all lengths of substring that will 'fit'. This yields all possible substrings; we can use list comprehension notation to make a list of them very easily.