Tuple of distinct characters in a list of strings in Python


This Python code creates a tuple called distinct_chars, which contains all the distinct characters from the strings in the strings list. Here's how the code works:

  • strings = ["apple", "banana", "cherry"]: This line initializes a variable named strings and assigns it a list containing three strings.
  • distinct_chars = tuple(char for string in strings for char in string): This line of code initializes a variable named distinct_chars and assigns it a tuple created using a nested generator expression.
    • for string in strings: This outer part of the code sets up a loop that iterates through each string string in the strings list.
    • for char in string: This inner part of the code sets up a nested loop that iterates through each character char in the current string.
    • char: For each character in each string, it includes the character in the generator expression.
    • tuple(...): This surrounds the nested generator expression and converts the generated characters into a tuple.
  • print(strings): This line of code prints the original strings list to the console.
  • print(distinct_chars): This line of code prints the distinct_chars tuple (which contains the distinct characters from the strings) to the console.

Source Code

strings = ["apple", "banana", "cherry"]
distinct_chars = tuple(char for string in strings for char in string)
print(strings)
print(distinct_chars)

Output

['apple', 'banana', 'cherry']
('a', 'p', 'p', 'l', 'e', 'b', 'a', 'n', 'a', 'n', 'a', 'c', 'h', 'e', 'r', 'r', 'y')

Example Programs