Python List Comprehension
List Comprehension :
List comprehensions provide a concise and elegant way to create lists.
List comprehension is more compact and faster than normal functions and loops for creating list.
We can create lists just like mathematical statements and in one line only
The list comprehension always returns a result list.
Syntax :
It consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can be anything, meaning you can put in all kinds of objects in lists.
The result will be a new list resulting from evaluating the expression.
A list comprehension generally consist of these parts : 1. Output expression, 2. input sequence, 3. a variable representing member of input sequence and an optional predicate part. [ expression for item in list if conditional ] Above Syntax is equivalent to: for item in list: if conditional: expression
Example : Create a list that contains number from 0 to 9.
my_list = [] for i in range(10): my_list.append(i) print(my_list) [OUTPUT] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
We can do the same by list comprehension in one line as
my_list = [i for i in range(10)] print(my_list) [OUTPUT] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Conditions in List Comprehension
# below list contains square of all odd numbers from # range 1 to 10 odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1] print(odd_square) [OUTPUT] [1, 9, 25, 49, 81] # Without list comprehension odd_square = [] for x in range(1, 11): if x % 2 == 1: odd_square.append(x**2) print(odd_square)
The list ,odd_square, will be populated square of number, by the items in range from 1-11 if the item's value is not divisible by 2.
Nested if with List Comprehension
# below list contains numbers from 0 to 100 # which are divided by 2 and 5 num_list = [x for x in range(100) if x % 2 == 0 if x % 5 == 0] print(num_list) [OUTPUT] [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] # Without list comprehension num_list = [] for x in range(100): if x % 2 == 0: if x % 5 == 0: num_list.append(x) print(num_list)
if...else with List Comprehension
my_list = ["even" if i%2==0 else "odd" for i in range(10)] print(my_list) [OUTPUT] ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
Nested loops in List Comprehension
Example :Write a Python program to find Transpose of matrix :
transposed = [] matrix = [[1, 2, 3, 4], [4, 5, 6, 8]] for i in range(len(matrix[0])): transposed_row = [] for row in matrix: transposed_row.append(row[i]) transposed.append(transposed_row) print(transposed) [OUTPUT] [[1, 4], [2, 5], [3, 6], [4, 8]]
As we can see, in the above code we are using two for loops to find the transpose of matrix.
Let's see how to do nested iteration inside a list comprehension.
Transpose of a Matrix using List Comprehension
matrix = [[1, 2, 3, 4], [4, 5, 6, 8]] transpose = [[row[i] for row in matrix] for i in range(4)] print (transpose) [OUTPUT] [[1, 4], [2, 5], [3, 6], [4, 8]]
The nested loops in list comprehension don’t work like normal nested loops. In the above program, for i in range(4) is executed before row[i] for row in matrix. Hence at first, a value is assigned to i then item directed by row[i] is appended in the transpose variable.
NOTE: Remember, every list comprehension can be rewritten in for loop, but every for loop can’t be rewritten in the form of list comprehension.
Some Python program to demonstrate list comprehension
# below list contains square of all odd numbers from # range 1 to 10 odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1] print(odd_square) [OUTPUT] [1, 9, 25, 49, 81]
# below list contains power of 2 from 1 to 8 power_of_2 = [2 ** x for x in range(1, 9)] print(power_of_2) [OUTPUT] [2, 4, 8, 16, 32, 64, 128, 256]
# below list contains prime and non-prime in range 1 to 50 noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] primes = [x for x in range(2, 50) if x not in noprimes] print(primes) [OUTPUT] [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
# list for lowering the characters print([x.lower() for x in ["A","B","C"]]) [OUTPUT] ['a', 'b', 'c']
# list which extracts number string = "my phone number is : 11122 !!" print("\nExtracted digits") numbers = [x for x in string if x.isdigit()] print(numbers) [OUTPUT] Extracted digits ['1', '1', '1', '2', '2']
# A list of list for multiplication table a = 5 table = [[a, b, a * b] for b in range(1, 11)] print("\nMultiplication Table") for i in table: print(i) [OUTPUT] Multiplication Table [5, 1, 5] [5, 2, 10] [5, 3, 15] [5, 4, 20] [5, 5, 25] [5, 6, 30] [5, 7, 35] [5, 8, 40] [5, 9, 45] [5, 10, 50]
Next topic is Tuple
Training For College Campus
We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies
like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.
Please mail your requirement at info@prowessapps.in
Projects For Students
Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.
Students can mail requirement at info@prowessapps.in