List Comprehension
Which one is easier to debug, loop or list comprehension? Way would you use list comprehension? Does square brackets used for set comprehension?
List Comprehension
""" We can write for loop more concisely using List Comprehension
"""
# Input string
S = "abcd"
# Loop (easier to debug)
R = []
for s in S:
if s in ['a', 'b', 'c']:
R.append(s.capitalize())
print(R)
# List comprehension (concise)
R = [s.capitalize() for s in S if s in ['a', 'b', 'c']]
print(R)
"""
['A', 'B', 'C']
['A', 'B', 'C']
"""
Set Comprehension
""" Set comprehension uses curly braches instead of square brackets
"""
# Input list
S = ['a', 'as', 'bat', 'car', 'rac', 'dove', 'python']
# List comprehension (square brackets)
L = [len(x) for x in S]
print(L)
# Set comprehension (curly braches, unique items)
U = {len(x) for x in S}
print(U)
"""
[1, 2, 3, 3, 3, 4, 6]
{1, 2, 3, 4, 6}
"""
Dictionary Comprehension
""" A Dictionary is a data type that stores data in key/value pair
"""
# Input dictionary
prices = {'milk': 1.02, 'coffee': 2.5, 'bread': 2.5}
# Dictionary comprehension
procent = 0.5
prices_new = {k: v*procent for (k, v) in prices.items() }
print(prices_new)
"""
{'milk': 0.51, 'coffee': 1.25, 'bread': 1.25}
"""
Last update: 111 days ago