DEV Community

Phondanai
Phondanai

Posted on

2

Bite-Size Python: List comprehensions

This mini-tutorial is demonstrate how I use list comprehensions in Python.

Let's start!

  • List creation
# normally
>>> a_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# then
>>> a_list = [i for i in range(11)] # but actually you just use list(range(11)) :P 
  • Conditional filtering using if
>>> a_list_even = [i*i for i in range(11) if i % 2 == 0]
>>> a_list_even_doubled
[0, 4, 16, 36, 64, 100]
  • You can work with other data type rather than list too
>>> a_dict = {
    "mango": 20,
    "grape": 30,
    "durian": 100,
    "latte": 40,
    "cappuccino": 30
}
>>> fruits = ["mango", "grape", "durian"]
>>> fruit_prices = [(k, v) for k, v in a_dict.items() if k in fruits]
>>> fruit_prices
[('mango', 20), ('grape', 30), ('durian', 100)] 

That's all.
Thank you for reading =)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay