List comprehensions are a super cool feature in python. As such, I’ve added a popular interview question to explain each part of the list comprehension constructor below.

A standard list comprehension is of the form:

newlist = [expression for item in iterable if condition == True]

where,

  • The iterable can be any iterable object, like a list, tuple, set etc.
  • The condition is like a filter that only accepts the items that evaluate to True (optional).
  • The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list.

Examples

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x if x != "banana" else "orange" for x in fruits]
['apple', 'orange', 'cherry', 'kiwi', 'mango']

Fizzbuzz List Comp

fizzbuzz = [
        # Replace with text if no remainder
        "fizz"*(not i%3) + "buzz"*(not i%5) +
        "fuzz"*(not i%7) + "bizz"*(not i%9) +
        "zuzz"*(not i%33) + "zizz"*(not i%55) +
        "mizz"*(not i%77) + "muzz"*(not i%99)
        # Otherwise return the integer if string is empty
        or str(i)
        # Iterate over 1 to 100
        for i in range(1, 101)
        # Choose what to keep
        if i % 1 == 0
        if 50 < i < 77
    ]
fizz
52
53
fizzbizz
buzzzizz
fuzz
fizz
58
59
fizzbuzz
61
62
fizzfuzzbizz
64
buzz
fizzzuzz
67
68
fizz
buzzfuzz
71
fizzbizz
73
74
fizzbuzz
76

Dictionary Comprehensions

Object can be a dictionary or list etc.

dict = {key:value for key, value in object}