InterviewSolution
| 1. |
What are Dict and List comprehensions? |
|
Answer» Python comprehensions, like DECORATORS, are syntactic sugar constructs that help build altered and filtered lists, dictionaries, or SETS from a given list, dictionary, or set. Using comprehensions saves a lot of time and code that might be considerably more verbose (containing more LINES of code). Let's check out some examples, where comprehensions can be truly beneficial:
Comprehensions allow for multiple iterators and hence, can be used to combine multiple lists into one. a = [1, 2, 3]b = [7, 8, 9][(x + y) for (x,y) in zip(a,b)] # parallel iterators# output => [8, 10, 12][(x,y) for x in a for y in b] # nested iterators# output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)]
A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or work upon its inner elements. my_list = [[10,20,30],[40,50,60],[70,80,90]]flattened = [x for temp in my_list for x in temp]# output => [10, 20, 30, 40, 50, 60, 70, 80, 90]
|
|