Page 307 - CTS - CSA TP - Volume 2
P. 307
COMPUTER SOFTWARE APPLICATION - CITS
v
EXERCISE 135 : Construct and analyze code segments
that include List comprehensions,
tuple, set and Dictionary comprehensions
Objectives
At the end of this exercise you shall be able to
• develop python programs to Construct and analyze code segments that include List comprehensions,
tuple, set and Dictionary comprehensions
Procedure
Comprehensions in Python provide a concise way to create and manipulate sequences (lists, sets, dictionaries,
etc.) based on existing sequences. There are mainly three types of comprehensions: list comprehensions, set
comprehensions, and dictionary comprehensions.
1 List Comprehensions:
List comprehensions allow you to create new lists by applying an expression to each item in an existing
iterable (list, tuple, string, etc.). They are a concise alternative to using loops.
Syntax:
new_list = [expression for item in iterable if condition]
TASK 1: Squares of Numbers
Code:
squares = [x**2 for x in range(1, 6)]
print(“Squares of numbers:”, squares)
Explanation:
This list comprehension creates a list of squares of numbers from 1 to 5.
Output:
TASK 2: Even Numbers
Code:
even_numbers = [x for x in range(10) if x % 2 == 0]
print(“Even numbers:”, even_numbers)
Explanation:
Explanation: This list comprehension generates a list of even numbers between 0 and 9.
Output:
292