DEV Community

Phondanai
Phondanai

Posted on

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 =)

Top comments (0)