List comprehension python
List comprehension is a technique to create new list in a very simple and effective way. Which using expression, conditions and iterable objects to generate new resulting list. Syntax of this as follows.
list = [expression for item in iterable if condition]
Here iterable can be (range,string,set,tuple and list) etc. Condition is optional, and this are returns a new list.
Example 1
# Example 1
num = [x for x in range(1,6)]
# Display result list
print(num)

[1, 2, 3, 4, 5]
Example 2
# Example 2
num = [1, 2, 3, 4, 5, 6, 10]
# Collecting odd element from given number
# here condition is if (x % 2 == 0)
result = [x for x in num if x % 2 == 0]
# Display result list
print(result)

[2, 4, 6, 10]
Example 3
# Example 3
result = [c for c in "Like"]
# Display result list
print(result)
['L', 'i', 'k', 'e']
Example 4
# Example 4
matrix = [[1,2,3],[4,5,6],[7,8,9]]
result = [[col[x] for col in matrix] for x in range(len(matrix))]
# Display result list
print(result)

[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment