Learn how you can become a Python programmer in just 12 weeks.

    We respect your privacy. Unsubscribe at anytime.

    Master List and Dict Comprehension with Python

    How to use List and Dict Comprehension in Python

    What is List Comprehension in Python? You will learn how to make List Comprehension and show how this also works with dictionaries, called Dict Comprehension. Then show how Dict Comprehension can be used for frequency count.

    In this tutorial, you will:

    • Understand List Comprehension in Python: Learn the concept and syntax of List Comprehension, a concise way to create lists based on existing lists or iterables.
    • Explore Dict Comprehension: Discover how List Comprehension extends to dictionaries, known as Dict Comprehension, enabling the creation of dictionaries in a similar concise manner.
    • Utilize Dict Comprehension for Frequency Count: Learn how Dict Comprehension can be used to efficiently perform frequency counting on elements within a list or iterable.

    By the end of the tutorial, you will have a solid understanding of List Comprehension and Dict Comprehension in Python. You will be able to leverage these powerful techniques to create lists and dictionaries more efficiently and apply them to perform frequency counting tasks effectively.

    Watch tutorial

    Step 1: What is List Comprehension in Python?

    List Comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists.

    Wikipedia.org

    It is easiest to demonstrate how to create it in Python (see more about lists and about foo-loops).

    my_list = [i for i in range(10)]
    print(my_list)
    

    Will result in.

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Here you use the range(10) construct, which gives a sequence from 0 to 9 that can be used in the Comprehension construct.

    A more direct example is given here.

    my_new_list = [i*i for i in my_list]
    print(my_new_list)
    

    Which results in the following.

    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    

    Step 2: List Comprehension with if statements

    Let’s get straight to it (see more about if-statements).

    my_list = [i for i in range(10) if i % 2 == 0]
    print(my_list)
    

    This will result in.

    [0, 2, 4, 6, 8]
    

    Also, you can make List Comprehension with if-else-statements.

    my_list = [i if i % 2 else -i for i in range(10)]
    print(my_list)
    

    This results in.

    [0, 1, -2, 3, -4, 5, -6, 7, -8, 9]
    

    Step 3: Dict Comprehension in Python

    Let’s dive straight into it (see more about dict).

    my_list = [i for i in range(10)]
    my_dict = {i: i*i for i in my_list}
    print(my_dict)
    

    Which results in.

    {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
    

    Notice, that the lists do not need to contain integers or floats. The constructs also work with any other values.

    Step 4: Frequency Count using Dict Comprehension

    This is amazing.

    text = 'aabbccccc'
    freq = {c: text.count(c) for c in text}
    print(freq)
    

    Which results in.

    {'a': 2, 'b': 2, 'c': 5}
    

    Notice, that here we will recount each instance of the letters. To avoid that you can do as follows.

    text = 'aabbccccc'
    freq = {c: text.count(c) for c in set(text)}
    print(freq)
    

    Which results in the same output. The difference is that you only count for each letter once.

    Step 5: Want more?

    I am happy you asked. Now you have learned about List and Dict Comprehension in Python.

    In the next project you will Master Object-Oriented Programming by Creating a Card Game.

    If this is something you like and you want to get started with Python, then this is part of an 8 hours FREE video course with full explanations, projects on each level, and guided solutions.

    The course is structured with the following resources to improve your learning experience.

    • 17 video lessons teaching you everything you need to know to get started with Python.
    • 34 Jupyter Notebooks with lesson code and projects.
    • A FREE eBook┬áto support your Python learning.

    See the full FREE course page here.

    Python for Finance: Unlock Financial Freedom and Build Your Dream Life

    Discover the key to financial freedom and secure your dream life with Python for Finance!

    Say goodbye to financial anxiety and embrace a future filled with confidence and success. If you’re tired of struggling to pay bills and longing for a life of leisure, it’s time to take action.

    Imagine breaking free from that dead-end job and opening doors to endless opportunities. With Python for Finance, you can acquire the invaluable skill of financial analysis that will revolutionize your life.

    Make informed investment decisions, unlock the secrets of business financial performance, and maximize your money like never before. Gain the knowledge sought after by companies worldwide and become an indispensable asset in today’s competitive market.

    Don’t let your dreams slip away. Master Python for Finance and pave your way to a profitable and fulfilling career. Start building the future you deserve today!

    Python for Finance a 21 hours course that teaches investing with Python.

    Learn pandas, NumPy, Matplotlib for Financial Analysis & learn how to Automate Value Investing.

    “Excellent course for anyone trying to learn coding and investing.” – Lorenzo B.

    2 thoughts on “Master List and Dict Comprehension with Python”

    Leave a Comment