Page 309 - CTS - CSA TP - Volume 2
P. 309
COMPUTER SOFTWARE APPLICATION - CITS
Set Comprehensions:
A set is an unordered and mutable collection of unique elements. It is defined using curly braces {}. Sets
are widely used when the presence of unique elements is crucial, and the order of elements doesn’t matter.
Set comprehensions are similar to list comprehensions but create sets instead. They use curly braces {}.
Syntax:
new_set = {expression for item in iterable if condition}
TASK 5: Cube of numbers from 1 to 5
Code:
set_of_cubes = {x**3 for x in range(1, 6)}
print(“Set of cubes:”, set_of_cubes)
Explanation:
• range(1, 6) generates numbers from 1 to 5 (inclusive).
• x**3 computes the cube of each number in the range.
• The set comprehension {x**3 for x in range(1, 6)} collects these cube values into a set.
After executing the code, the set set_of_cubes will contain the cubes of numbers 1 through 5. The output will
look like:
TASK 6: Set Comprehension with Conversion
Code:
# Create a set of uppercase characters in a string
text = “hello World”
print(“Given Text is : “,text)
uppercase_set = {char.upper() for char in text if char.isalpha()}
print(“Set of uppercase characters:”, uppercase_set)
Explanation:
1 text = “hello World”: Initializes a string variable named text with the value “hello World”.
2 print(“Given Text is : “, text): Prints the original text.
3 uppercase_set = {char.upper() for char in text if char.isalpha()}:
• This is a set comprehension.
• for char in text: Iterates over each character in the text.
• if char.isalpha(): Filters out non-alphabetic characters.
• char.upper(): Converts each character to uppercase.
• The result is a set containing the uppercase alphabetic characters from the original text.
4 print(“Set of uppercase characters:”, uppercase_set): Prints the set of uppercase characters obtained from the
text.
294
CITS : IT & ITES - Computer Software Application - Exercise 135