Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Ds Using Python Exp4

Uploaded by

vineethaiml
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Ds Using Python Exp4

Uploaded by

vineethaiml
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

4.

Write a Python program to illustrate the following comprehensions:

a) List Comprehensions b) Dictionary Comprehensions

c) Set Comprehensions d) Generator Comprehensions

a) List Comprehensions

Using Loop:

#Constructing output list WITHOUT using List comprehensions


input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
output_list = []
#Using loop for constructing output list
for var in input_list:
if var % 2 == 0:
output_list.append(var)
print(“Output List using for loop:”, output_list)

Using List Comprehension:

# Using List comprehensions


# for constructing output list
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
list_using_comp = [var for var in input_list if var % 2 == 0]
print("Output List using list comprehensions:",list_using_comp)

b) Dictionary Comprehensions

Using Loop:

state = ['Gujarat', 'Maharashtra', 'Rajasthan']


capital = ['Gandhinagar', 'Mumbai', 'Jaipur']
output_dict = {}
# Using loop for constructing output dictionary
for (key, value) in zip(state, capital):
output_dict[key] = value
print("Output Dictionary using for loop:", output_dict)
Using Dictionary Comprehension:

# Using Dictionary comprehensions

# for constructing output dictionary

state = ['Gujarat', 'Maharashtra', 'Rajasthan']

capital = ['Gandhinagar', 'Mumbai', 'Jaipur']

dict_using_comp = {key:value for (key, value) in zip(state, capital)}

print("Output Dictionary using dictionary comprehensions:",dict_using_comp)

C) Set Comprehensions

Using Loop:

input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
output_set = set()
# Using loop for constructing output set
for var in input_list:
if var % 2 == 0:
output_set.add(var)
print("Output Set using for loop:", output_set)

Using Set Comprehension :

# Using Set comprehensions


# for constructing output set
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
set_using_comp = {var for var in input_list if var % 2 == 0}
print("Output Set using set comprehensions:",set_using_comp)
Generator Comprehensions

Using Generator Comprehensions

input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]

output_gen = (var for var in input_list if var % 2 == 0)

print("Output values using generator comprehensions:", end = ' ')

for var in output_gen:

print(var, end = ' ')

You might also like