List and dictionary comprehensions in Python

List and dictionary comprehensions in Python

List Comprehension

L = [1,2,3,4,5,6,7,8,9,10] # dummy dataE = [num for num in L if num%2 == 0]print(E)
[2, 4, 6, 8, 10]
L = [1,2,3,4,5,6,7,8,9,10] # dummy dataE = [] # empty listfor num in L: 
if num%2 == 0:
E.append(num)
print(E)
[2, 4, 6, 8, 10]
L = [1,2,3,4,5,6,7,8,9,10] # dummy dataL2 = [num**2 for num in L if num%2 != 0]print(L2)
[1, 9, 25, 49, 81]
L = [1,2,3,4,5,6,7,8,9,10] # dummy dataL2 = [] # empty listfor num in L: 
if num%2 != 0:
L2.append(num**2)
print(L2)
[1, 9, 25, 49, 81]

Dictionary Comprehension

dict_ft = {“Ram”: 5.5, “Shyam”: 6.1, “Amin”: 5.2}print(dict_ft)
{‘Ram’: 5.5, ‘Shyam’: 6.1, ‘Amin’: 5.2}
dict_cm = {key: round(value*30.48,2) for (key, value) in dict_ft.items()}# 1 foot = 30.48 cmprint(dict_cm)
{‘Ram’: 167.64, ‘Shyam’: 185.93, ‘Amin’: 158.5}
dict_person = {“Lucas”: 45, “Stano”: 65, “Peter”: 59, “Hana”: 69, “Eva”: 23}print(dict_person)
{‘Lucas’: 45, ‘Stano’: 65, ‘Peter’: 59, ‘Hana’: 69, ‘Eva’: 23}
dict_age = {key: (“Old” if value > 60 else “Young”) for (key, value) in dict_person.items()} print(dict_age)
{‘Lucas’: ‘Young’, ‘Stano’: ‘Old’, ‘Peter’: ‘Young’, ‘Hana’: ‘Old’, ‘Eva’: ‘Young’}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store