What are Dict and List Comprehensions in Python?

Dictionary and list comprehensions are just concise way to define dictionaries and lists.

Example of list comprehension is:

Var = [i for i in range (5)]

The above code created a list as below-

[0, 1, 2, 3, 4] 

Example of dictionary comprehension is –

X = [i : i + 2 for I in range(5)]

The above code created a list as below –

[0: 2, 1: 3, 2: 4, 3: 5, 4: 6]

Popular Posts

Spread the knowledge
 
  

Leave a Reply

Your email address will not be published. Required fields are marked *