What is List Comprehensive in Python
Published on: December 27, 2024
List comprehension is a concise and efficient way to create and manipulate lists in Python. It allows you to generate new lists by applying an expression to each item in an existing iterable (like a list, tuple, string, or range) and optionally filtering the items based on a condition.
[expression for item in iterable if condition]
expression: The expression that is evaluated for each item in the iterable and added to the new list. item: The variable representing each element in the iterable. iterable: The collection (like a list, range, string, etc.) that you are looping over. condition (optional): A conditional expression to filter which items should be included in the new list.
Below are different range of examples.
# To Print All Even Numbers
L = [i for i in range(1,11)] [i for i in range(1,11) if i%2 ==0]
Output : [2, 4, 6, 8, 10]
# Scalar multiplication on a vector
v = [2,3,4] s = -3 [s*i for i in v]
Output : [[-6, -9, -12]]
# Print all numbers divisible by 5 in the range of 1 to 50
[i for i in range(1,51) if i%5 == 0] Output : [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
# Nested if with List Comprehension
# add new list from my_fruits and items if the fruit exists in basket and also starts with 'a' basket = ['apple','guava','cherry','banana'] my_fruits = ['apple','kiwi','grapes','banana'] [i for i in my_fruits if i in basket and i.startswith('a')] Output : ['apple']
# Print a (3,3) matrix using list comprehension -> Nested List comprehension
[[i*j for i in range(1,4)] for j in range(1,4)] Output : [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
# cartesian products -> List comprehension on 2 lists together
L1 = [1,2,3,4] L2 = [5,6,7,8] [i*j for i in L1 for j in L2] Output : [5, 6, 7, 8, 10, 12, 14, 16, 15, 18, 21, 24, 20, 24, 28, 32]
# Remove vowels from a string
words = ['apple', 'banana', 'cherry'] [''.join([i for i in j if i not in ('a','e','i','o','u')]) for j in words] Output : ['ppl', 'bnn', 'chrry']
# Multiply elements of two lists element-wise
list1 = [1, 2, 3] list2 = [4, 5, 6] [list1[i]*list2[j] for i in range(0,len(list1)) for j in range(0,len(list2)) if i==j] Output : [4, 10, 18]
# Extract digits from a string
words = ['abc123', 'test456', 'hello', '789'] [''.join([i for i in j if i.isnumeric()])for j in words] Output : ['123', '456', '', '789']
# Write a list comprehension that can transpose a given matrix
matrix = [[1,2,3],[4,5,6],[7,8,9]] [[m[i][j] for i in range(0,len(m))] for j in range(0,len(m))] Output : [[m[i][j] for i in range(0,len(m))] for j in range(0,len(m))]
# Write a list comprehension to print the following matrix [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
[[i*3+j for j in range(3)] for i in range(3)] Output : [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
# Convert Character Matrix to single String using string comprehension.
Input: [['c', 'a', 'm', 'p', 'u', 'x'], ['i', 's'], ['b', 'e', 's', 't'], ['c', 'h', 'a', 'n', 'n', 'e', 'l']] ' '.join([''.join(i) for i in L]) Output: campux is best channel
Advantages of List Comprehension:
1.) Concise: It's shorter than using traditional for loops, making your code cleaner and easier to understand.
2.) Faster Execution: In many cases, list comprehensions are faster than equivalent for loops because they are optimized internally by Python.
3.) Readability: It reduces the need for more complex loops, which improves the readability of your code.
In summary, list comprehension is a powerful feature in Python that allows you to create and manipulate lists more efficiently and concisely, making your code both cleaner and faster.
Happy Learning!!!! 😀