Created
December 20, 2020 20:26
-
-
Save Nayemjaman/ac9593fcb577892c9b8ea4311fe377ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
a = [] | |
for i in range(13): | |
a.append(i) | |
print(a) | |
outPut:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] | |
can convert this code in one line with | |
List Comprehension: | |
""" | |
print([i for i in range(13)]) | |
#outPut:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] | |
print([[i for i in range(3)] for j in range(2)]) | |
#outPut:[[0, 1, 2],[0, 1, 2]] | |
#More Example | |
i = [x for x in range(5)] | |
n = [y+5 for y in i] | |
print(n) | |
#[5, 6, 7, 8, 9] | |
""" | |
a = {} | |
for i in range(13): | |
a.append(i) | |
print(a) | |
#outPut:{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} | |
Set Comprehension: | |
""" | |
i = {x for x in range(5)} | |
n = {y*5 for y in i} | |
print(n) | |
#output:{0, 5, 10, 15, 20} | |
""" | |
Dictionary Comprehension: | |
""" | |
x = (i for i in range(5)) | |
y = (j for j in range(6,10)) | |
z = zip(x, y) | |
print(list(z)) | |
#outPut:[(0, 6), (1, 7), (2, 8), (3, 9)] | |
#More Example | |
l1 = [x for x in range(5)] | |
l2 = ['Sun','Mon','Tue','Wed','Thu'] | |
n ={key:value for (key, value) in zip(l1, l2)} | |
print(n) | |
#outPut:{0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu'} | |
""" | |
generator comprehension | |
""" | |
print((i for i in sample_li)) | |
# convert to iterable | |
print(list(i for i in sample_li)) | |
print(set(i for i in sample_li)) | |
#There is no tuple comprehension but we can use generator comprehension like this | |
print(tuple(i for i in sample_li)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment