Python: List Comprehensions are better

Using List Comprehensions, we don’t have to write ‘lamda’ expressions to map or filter values and the code is simpler.

dct_lst = [{'key1': 1, 'key2': 2}, {'key1': 2, 'key2': 3}]

# using list comprehension
result = [x['key2'] * 10 for x in dct_lst if x['key1'] == 1]
print result
# [20]

# using map() and filter()
result = map(lambda x: x['key2'] * 10,
    filter(
        lambda x: x['key1'] == 1,
        dct_list
    )
)
print result
# [20]

 

Leave a Reply

Your email address will not be published. Required fields are marked *