1.

Comprehensions in Python

Answer»

  • List Comprehensions:
    It is a shorter syntax to create a new list using values of an existing list.
a = [0, 1, 2, 3]
# b will store values which are 1 greater than the values stored in a
b = [i + 1 for i in a]
print(b)
Output:
[1, 2, 3, 4]

  • Set Comprehension:
     It is a shorter syntax to create a new set using values of an existing set.
a = {0, 1, 2, 3}
# b will store squares of the elements of a
b = {i ** 2 for i in a}
print(b)
Output:
{0, 1, 4, 9}

  • Dict Comprehension:
     It is a shorter syntax to create a new dictionary using values of an existing dictionary.
a = {'Hello':'World', 'First': 1}
# b stores elements of a in value-key pair format
b = {val: k for k , val in a.items()}
print(b)
Output:
{'World': 'Hello', 1: 'First'}


Discussion

No Comment Found