Conditionals in List Comprehension
We can also add conditional statements to the list comprehension. We can create a list using range(), operators, etc. and cal also apply some conditions to the list using the if statement.
Key Points
- Comprehension of the list is an effective means of describing and constructing lists based on current lists.
- Generally, list comprehension is lightweight and simpler than standard list formation functions and loops.
- We should not write long codes for list comprehensions in order to ensure user-friendly code.
- Every comprehension of the list can be rewritten in for loop, but in the context of list interpretation, every for loop can not be rewritten.
Below are some examples which depict the use of list comprehensions rather than the traditional approach to iterate through iterable:
Python List Comprehension using If-else.
In the example, we are checking that from 0 to 7 if the number is even then insert Even Number to the list else insert Odd Number to the list.
Python
lis = [ "Even number" if i % 2 = = 0 else "Odd number" for i in range ( 8 )] print (lis) |
Output
['Even number', 'Odd number', 'Even number', 'Odd number', 'Even number', 'Odd number', 'Even number', 'Odd number']
Nested IF with List Comprehension
In this example, we are inserting numbers in the list which is a multiple of 10 to 100, and printing it.
Python
lis = [num for num in range ( 100 ) if num % 5 = = 0 if num % 10 = = 0 ] print (lis) |
Output
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
Display a square of numbers from 1 to 10
In this example, we are inserting a square from 1 to 10 to list and printing the list.
Python
# Getting square of number from 1 to 10 squares = [n * * 2 for n in range ( 1 , 11 )] # Display square of even numbers print (squares) |
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Display Transpose of 2D- Matrix
In this example, we are making a transpose of the matrix using list comprehension.
Python
# Assign matrix twoDMatrix = [[ 10 , 20 , 30 ], [ 40 , 50 , 60 ], [ 70 , 80 , 90 ]] # Generate transpose trans = [[i[j] for i in twoDMatrix] for j in range ( len (twoDMatrix[ 0 ]))] print (trans) |
Output
[[10, 40, 70], [20, 50, 80], [30, 60, 90]]
Toggle the case of each character in a String
In this example, we toggle the case of each character in a given string using the XOR operator with 32 and store the result in a list.
Python
# Initializing string string = 'Geeks4Geeks' # Toggle case of each character List = list ( map ( lambda i: chr ( ord (i) ^ 32 ), string)) # Display list print ( List ) |
Output
['g', 'E', 'E', 'K', 'S', '\x14', 'g', 'E', 'E', 'K', 'S']
Reverse each string in a Tuple
In this example, we are reversing strings in for loop and inserting them into the list, and printing the list.
Python
# Reverse each string in tuple List = [string[:: - 1 ] for string in ( 'Geeks' , 'for' , 'Geeks' )] # Display list print ( List ) |
Output
['skeeG', 'rof', 'skeeG']
Creating a list of Tuples from two separate Lists
In this example, we have created two lists of names and ages. We are using zip() in list comprehension and we are inserting the name and age as a tuple to list. Finally, we are printing the list of tuples.
Python
names = [ "G" , "G" , "g" ] ages = [ 25 , 30 , 35 ] person_tuples = [(name, age) for name, age in zip (names, ages)] print (person_tuples) |
Output:
[('G', 25), ('G', 30), ('g', 35)]
Display the sum of digits of all the odd elements in a list.
In this example, We have created a list and we are finding the digit sum of every odd element in the list.
Python
# Explicit function def digitSum(n): dsum = 0 for ele in str (n): dsum + = int (ele) return dsum # Initializing list List = [ 367 , 111 , 562 , 945 , 6726 , 873 ] # Using the function on odd elements of the list newList = [digitSum(i) for i in List if i & 1 ] # Displaying new list print (newList) |
Output
[16, 3, 18, 18]
Python – List Comprehension
A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list.
Example:
Python
numbers = [ 12 , 13 , 14 ,] doubled = [x * 2 for x in numbers] print (doubled) |
Output
[24, 26, 28]