Skip to content

Commit 177c1d3

Browse files
committed
List Comprehensions
1 parent dd90335 commit 177c1d3

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Programs/P50_ListComprehensions.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Author: OMKAR PATHAK
2+
# In this example we will see how to write list comprehensions to make our tasks easier
3+
4+
# Python.org says:
5+
# List comprehensions provide a concise way to create lists.
6+
# Common applications are to make new lists where each element is
7+
# the result of some operations applied to each member of another sequence
8+
# or iterable, or to create a subsequence of those elements that satisfy a certain condition.
9+
10+
numbers = []
11+
for i in range(10):
12+
numbers.append(i)
13+
print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
14+
15+
# Side Effect of above operation:It creates a variable(or overwrites) named 'x'
16+
# that still exists after the loop completes. To get rid of this Side Effect we use List comprehensions.
17+
18+
# List comprehension:
19+
numbers = [i for i in range(10)]
20+
print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
21+
22+
# Let us see few more examples
23+
squares = [i * i for i in range(10)]
24+
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
25+
26+
# This is same as:
27+
squares = []
28+
for i in range(10):
29+
squares.append(i * i)
30+
31+
# Some more:
32+
odds = [i for i in numbers if i % 2 != 0]
33+
print(odds) # [1, 3, 5, 7, 9]
34+
35+
# This is same as:
36+
odds = []
37+
for i in numbers:
38+
if i % 2 != 0:
39+
odds.append(i)
40+
41+
# We can also use functions in comprehensions
42+
def isSqaure(x):
43+
import math
44+
sqrt = int(math.sqrt(x))
45+
return x == sqrt * sqrt
46+
47+
squares = [x for x in range(100) if isSqaure(x) == True]
48+
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
49+
50+
# Some Complex comprehensions:
51+
pairs = [[x, x * x] for x in numbers]
52+
print(pairs) # [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

0 commit comments

Comments
 (0)