Distinct characters from multiple strings with case insensitivity as a tuple in Python


This Python code processes a list of strings, strings, and creates a tuple named distinct_case_insensitive_chars. The tuple contains distinct characters (case-insensitive) from all the strings in the list. Here's how the code works:

  • strings = ["apple", "Banana", "Cherry"]: This line initializes a variable named strings and assigns it a list of three strings, including mixed-case characters.
  • distinct_case_insensitive_chars = tuple(...): This line initializes a variable named distinct_case_insensitive_chars and assigns it a tuple created by using a generator expression.
    • (... for string in strings for char in string): The generator expression iterates through each string in the strings list and then iterates through each character in each string.
    • char.lower() for ...: For each character char, it converts the character to lowercase using the lower() method. This ensures that the characters are treated in a case-insensitive manner.
  • set(...): The set() function is used to ensure that only distinct characters are retained. Since sets do not allow duplicate elements, this operation automatically eliminates duplicate characters.
  • tuple(...): Finally, the set of case-insensitive characters is converted to a tuple.
  • print(strings): This line of code prints the original strings list to the console.
  • print(distinct_case_insensitive_chars): This line of code prints the distinct_case_insensitive_chars tuple to the console.

Source Code

strings = ["apple", "Banana", "Cherry"]
distinct_case_insensitive_chars = tuple(set(char.lower() for string in strings for char in string))
print(strings)
print(distinct_case_insensitive_chars)

Output

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

Example Programs