7.3 List and Dictionary Comprehension#
You can use loops to generate lists and dictionaries with defined structures. You can use regular loops for this, but sometimes list and dictionary comprehension is more convenient.
Warning
This should only be used if you are interested in the list or dictionary specifically, not if you only intend to use them as iterators (as that is inefficient).
List Comprehension#
Lists can be generated by using the syntax:
[i for i in iterator]
where iterator
can be any iterator used in a loop. For example:
#Generating a list of integers in ascending order
numbers = [i for i in range(6)]
print(numbers)
[0, 1, 2, 3, 4, 5]
You can put any kind of code in the list, not only the iteration variable:
dots = ['.' * i for i in range(6)]
print(dots)
['', '.', '..', '...', '....', '.....']
You can treat the for
inside the list just like a for
loop, including looping through collections:
string = 'abcdefg'
#Generating a list of characters from a string
char_list = [char for char in string]
print(char_list)
['a', 'b', 'c', 'd', 'e', 'f', 'g']
Only use list comprehension if you are interested in the list itself. Do not use it in place of a for
loop.
You can also nest list comprehension:
print([[i + j for j in range(3)] for i in range(4) ])
[[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5]]
Dictionary Comprehension#
You can generate dictionaries in a similar way to lists using dictionary comprehension, with the syntax:
{k:v for k, v in iterator}
where iterator
needs to return pairs of keys and values. For example:
{k:v for k,v in enumerate(['val0', 'val1', 'val2'])}
{0: 'val0', 1: 'val1', 2: 'val2'}
Or
#List of keys
keys = ['a', 'b' , 'c', 'd']
#List of values
values = [1, 2, 3, 4]
dictionary = {k:v for k,v in zip(keys, values)}
print(dictionary)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Note, that you can alter the keys and values that are used:
#List of keys
keys = ['a', 'b' , 'c', 'd']
#List of values
values = [1, 2, 3, 4]
dictionary = {k.upper() : v / 10.0 for k,v in zip(keys, values)}
print(dictionary)
{'A': 0.1, 'B': 0.2, 'C': 0.3, 'D': 0.4}
It isn’t strictly necessary to loop through pairs of iteration variables:
{i.lower() : i.upper() for i in 'aBcdE'}
{'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E'}