Python Data Persistence – List Comprehension
Python supports many functional programming features. List comprehension is one of them. This technique follows mathematical set builder notation. It is a very concise and efficient way of creating a new list by performing a certain process on each item of the existing list. List comprehension is considerably efficient than processing a list by for loop.
Suppose we want to compute the 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:
Example
#new list with loop list1= [4,7,2,5,8] list2= [ ] for num in listl: sqr=num*num list2.append(sqr) print ('new list:', list2)
The new list will store squares of the existing list.
The list comprehension method achieves the same result more efficiently. List comprehension statement uses the following syntax:
new list = [x for x in sequence] |
We use the above format to construct a list of squares by using list comprehension.
- Python Program to Multiply Each Element of a List by a Number | How to Multiply Each Element in a List by a Number in Python?
- Python Program to Print all Perfect Squares from a List using List Comprehension and Math Module
- Python Program to Put Even and Odd elements in a List into Two Different Lists
Example
>>> list1=[ 4 , 7 , 2 , 5 , 8 ] >>> list2=[num*num for num in list1] >>> list2 [ 16 , 49 , 4 , 25 , 64 ] > > >
We can even generate a dictionary or tuple object as a result of list comprehension.
Example
>>> list1= [ 4 , 7 , 2 , 5 , 8 ] >>> dict1=[{num:num*num} for num in list1] >>> dict1 [{4 16}, {7: 49}, {2:4}, {5 : 25},{8 : 64 } ] >>>
List comprehension works with any iterable. Nested loops can also be used in a list comprehension expression. To obtain list of all combinations of characters from two strings:
Example
>>> list1= [x+y for x in 'ABC' for y in ' 123 ' ] >>> list1 [ 'A1' , 'A2', 'A3', 'B11,' B2 ', 'B3', 'Cl', 'C2', ' C3 '] >>>
The resulting list stores all combinations of one character from each string.
We can even have if condition in a list comprehension. The following statement will result in a list of all non-vowel alphabets in a string.
Example
>>> consonents=[char for char in "Simple is better than complex" if char not in [ 'a', 'e' , 'i' , 'o' , 'U' ] ] >>> consonents [ 'S' , 'm' , 'p' , '1' , ' ' , 'b' , 't' , 'r' , ' ' , 't' , 'h' , 'n' , ' ' , 'c' , 'm' , 'p' , 'l' , 'x' ]
Conditionals and looping constructs are the two most important tools in a programmer’s armory. Along with them, we also learned about controlling repetition with break and continue statements.
The next chapter introduces the concept of structured programming through the use of functions and modules.