InterviewSolution
| 1. |
Explain with example the technique of list comprehension in Python. |
|
Answer» List comprehension technique is similar to mathematical set builder notation. A classical for/while loop is generally used to traverse and process each ITEM in an iterable. List comprehension is considerably more efficient than processing a list by ‘for’ loop. It is a very concise mechanism of creating new list by performing a certain process on each item of existing list. Suppose we want to compute square of each number in a list and store squares in another list object. We can do it by a ‘for’ loop as shown below: squares=[] for num in range(6): squares.append(pow(num,2)) print (squares)The squares list object is DISPLAYED as follows: [0, 1, 4, 9, 16, 25]Same result is achieved by list comprehension technique MUCH more efficiently. List comprehension statement USES following syntax: newlist = [x for x in sequence]We use above format to construct list of squares using list comprehension. >>> numbers=[6,12,8,5,10] >>> squares = [x**2 for x in numbers] >>> squares [36, 144, 64, 25, 100]We can even generate a dictionary or tuple object as a result of list comprehension. >>> [{x:x*10} for x in range(1,6)] [{1: 10}, {2: 20}, {3: 30}, {4: 40}, {5: 50}]Nested loops can also be used in a list comprehension expression. To obtain list of all combinations of items from two lists (Cartesian product): >>> [{x:y} for x in range(1,3) for y in (11,22,33)] [{1: 11}, {1: 22}, {1: 33}, {2: 11}, {2: 22}, {2: 33}]The resulting list stores all combinations of one number from each list We can even have if condition in list comprehension. Following statement will result in list of all non-vowel alphabets in a string. >>> odd=[x for x in range(1,11) if x%2==1] >>> odd [1, 3, 5, 7, 9] |
|