Python: How comprehensions are used in Python programming.

 


Python comprehensions are one among the syntactic sugars of python which make coding look simple and easier. Comprehensions helps to save time and code.

Example1: Normal Comprehensions
    
my_list = [2, 3, 5, 7, 11]
squared_list = [x**2 for x in my_list]    # list comprehension
# output => [4 , 9 , 25 , 49 , 121]
squared_dict = {x:x**2 for x in my_list}    # dict comprehension
# output => {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49}

Example2 : List comprehension with conditional processing
my_list = [2, 3, 5, 7, 11]
squared_list = [x**2 for x in my_list if x%2 != 0]    # list comprehension
# output => [9 , 25 , 49 , 121]
squared_dict = {x:x**2 for x in my_list if x%2 != 0}    # dict comprehension
# output => {11: 121, 3: 9 , 5: 25 , 7: 49}

Comments

  1. It is a proficient article that you have shared here. I got some different kind of information from your article which I will be sharing with my friends who need this info. Thankful to you for sharing an article like this.Learn Python Programming for Kids

    ReplyDelete
    Replies
    1. Thanks for your inputs Amisina juniors academy.

      Delete
  2. Your blog contains lots of valuable data. It is a factual and beneficial article for us. Thankful to you for sharing an article like this.Abacus Franchisee

    ReplyDelete
  3. I am attracted by the presentation of this article. It is a genuinely a gainful article for us. Keep posting, Thank you.best vlsi training institutes in india

    ReplyDelete

Post a Comment