Tuple of distinct substrings from a word in Python


This Python code processes a single word, word, and creates a tuple called substrings. The substrings tuple contains all possible substrings of the word. Here's how the code works:

  • word = "hello": This line initializes a variable named word and assigns it the string "hello."
  • substrings = tuple(word[i:j+1] for i in range(len(word)) for j in range(i, len(word)): This line initializes a variable named substrings and assigns it a tuple created using a nested generator expression.
    • for i in range(len(word)): The outer loop iterates through the starting index i for substrings. It ranges from 0 to the length of the word.
    • for j in range(i, len(word)): The inner loop iterates through the ending index j for substrings. It ranges from the current value of i to the length of the word.
    • word[i:j+1]: For each combination of i and j, it slices the word from index i to index j+1, creating a substring.
    • tuple(...): This surrounds the nested generator expression and converts the generated substrings into a tuple.
  • print(word): This line of code prints the original word to the console.
  • print(substrings): This line of code prints the substrings tuple (which contains all possible substrings of the word) to the console.

Source Code

word = "hello"
substrings = tuple(word[i:j+1] for i in range(len(word)) for j in range(i, len(word)))
print(word)
print(substrings)

Output

hello
('h', 'he', 'hel', 'hell', 'hello', 'e', 'el', 'ell', 'ello', 'l', 'll', 'llo', 'l', 'lo', 'o')

Example Programs