Comprehensions for lists and dictionaries

Use comprehensions, lists, and dictionaries that are built as one-liners with the use of an iterator and a conditional when necessary:

a_list = [1,2,3,4,5] a_power_list = [value**2 for value in a_list] # the resulting list is [1, 4, 9, 16, 25] filter_even_numbers = [value**2 for value in a_list if value % 2 == 0] # the resulting list is [4, 16] 
another_list = ['a','b','c','d','e'] a_dictionary = {key:value for value, key in zip(a_list, another_list)} # the resulting dictionary is {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}

zip is a function that takes, as input, multiple lists of the same length and iterates through each element with the same index at the same time, so you can match the first elements ...

Get Python Data Science Essentials - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.