











Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Nested loops can be used in a comprehension expression of the list. ❑ In the example below, any combination of items from two lists in the form of a tuple is ...
Typology: Exercises
1 / 19
This page cannot be seen from the preview
Don't miss anything!












chars=[] for ch in ‘GKTCS INNOVATIONS’ : chars.append(ch) print(chars)
Example to uses a list comprehension to build a list of squares of the numbers between 1 and 10.
One of the applications of list comprehension is to flatten a list comprising of multiple lists into a single list
We can use nested if conditions with list comprehension.
❑ Like List Comprehension, Python allows dictionary comprehensions. ❑ We can create dictionaries using simple expressions. ❑ A dictionary comprehension takes the form {key: value for (key, value) in iterable}
We can use Dictionary comprehensions with if and else statements and with other expressions too.
old_price = {'milk': 1.02, 'coffee': 2.5, 'bread': 2.5} dollar_to_pound = 0. new_price = {item: value*dollar_to_pound for (item, value) in old_price.items()} print(new_price)
{'milk': 0.7752, 'coffee': 1.9, 'bread': 1.9}
original_dict = {'jack': 38 , 'michael': 48 , ‘ guido': 57 , 'john': 33 } new_dict = {k: v for (k, v) in original_dict.items() if v % 2 != 0 if v < 40} print(new_dict)
original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33} new_dict_1 = {k: ('old' if v > 40 else 'young') for (k, v) in original_dict.items()} print(new_dict_1)
{'jack': 'young', 'michael': 'old', 'guido ’: 'old', 'john': 'young'}