Enduring Effectiveness of List Comprehension in Python

List comprehension is a neat and aesthetic way to combine lists with for loop. For Example, you want to double items of a list -

x = [1, 2, 3]

y = [ ]

for item in x:

y.append(item*2)

List comprehension version -

y = [item*2 for item in x]

Result: y = [2, 4, 6]

Notice that there is not much change in syntax except the expression (i.e. item*2) moving at the start and complete doing away of .append method. You can go for more complex list comprehension following the same path.

Nested loop with list comprehension and if condition -

x = [1, 2, 3]

y = ['Red', 'Blue', 'Green']

z = []

z = [item*color for color in y for item in x if len(color)>3]

Result: z = ['Blue', 'BlueBlue', 'BlueBlueBlue', 'Green', 'GreenGreen', 'GreenGreenGreen']

#Python

#AIML

#datascience

要查看或添加评论,请登录

Viney S.的更多文章

  • Gen AI is "Intelligence as a Service"

    Gen AI is "Intelligence as a Service"

    The title of this small article/post is quote from Henrik Kniberg's unpausable (if that's not a word, it should legit…

    2 条评论
  • AI led Software Development

    AI led Software Development

    We already see Gen AI taking over run of the mill Coding tasks. What's next? AI creating a complete Software? On the…

  • My First AI Hackathon!

    My First AI Hackathon!

    What an exciting couple of days of Gen AI hackathon it was! Missed finals by whiskers (got Gen AI star award!) but…

    7 条评论
  • How not to be Mean about Average!

    How not to be Mean about Average!

    Couple of centuries back, there lived a renowned Statistics Professor in Indian subcontinent. The professor, proud of…

  • Population Boom-Bust and Elon Musk!

    Population Boom-Bust and Elon Musk!

    Let's all agree on one point - Elon Musk sparks debates like no-one! Whether it's making another planet habitable, his…

  • Type 1 - Type 2 Errors and Kalidasa

    Type 1 - Type 2 Errors and Kalidasa

    A recent post by Joshua Starmer PhD asked about the Data Science/ML terms that are generally confusing. Now for me Type…

    3 条评论

社区洞察

其他会员也浏览了