Resources
Lesson Objectives
Comprehensions in python
If Statement Comprehension
List Comprehensions
Dict Comprehensions
Are you Ready?
Summary
Intro
We've covered so much about python already, and I want to introduce you to my favorite concept - Comprehensions. They are great to create certain action in a single line.
Comprehensions allow you to write more compact, readable, and efficient code. Whether you're dealing with lists, dictionaries, sets, or even variables - comprehensions will save you time and effort. Plus, they make for some pretty impressive one-liners!
One-Liner refers to a piece of code that performs entire task in a single line. Many take it as a challenge and they try to compact their 100 lines of code into one single line. But that's an overkill and impossible to maintain.
So we will focus on the practical side of comprehensions in this lesson.
If Statement Comprehensions
Let's begin with simple if statement comprehensions. They are a great way to combine simple if/else
statement for defining data for your variables.
Think of the traditional way of creating if-else condition
Now, let's rewrite this with exactly the same result but using if statement comprehension:
Much cleaner, right?
It reduces multiple lines of code into a single one, and it's actually much easier to read an maintain. So you shouldn't be afraid of comprehensions. They can be even easier than the alternative.
List Comprehensions
Now it's time to focus on the most used comprehension in python - List Comprehensions.
They are a great way to transform, filter or create new lists in a more pythonic way. You will see me use them all the time once we go into Revit API.
And before I explain how to use them, let's imagine that you have a list of strings, and you would like to create a new list with all these strings in uppercase.
It's a very simple and straight-forward process:
Create a new list
Iterate through existing data
use upper() on a string
Add transformed string to a new list
Here is the code for that
And now let me use List Comprehensions to achieve exactly the same result
As you can see the second code is so much cleaner and easier to read than the first one, even though it's a simple task.
So let me explain Syntax Basics so you understand what's going on.
To create a list comprehension, you would create a list and write an expression inside. It will need 2 parts as the bare minimum.
What will be added to the list
Loop to iterate through items
And you can go crazy and write long statements here, but I would recommend to use comprehensions when they make your code much easier to read and maintain. That's the sacred rule.
Otherwise, stick to the traditional way.
List Comprehensions with Conditions
I hope you didn't think that it was the only way to create a list comprehension? We can also add conditions inside them, so we can filter out the data we are iterating over.
So, let's use the same example, but this time we want to ensure that items in a list have 'item_'
as a part of a string.
Here is the traditional way:
And now the same thing, but with list comprehension:
As you can see it still a one-liner, but it just got a bit longer because we added a condition statement in the end.
Here is a basic syntax breakdown:
List Comprehension - More Examples
Practice is the best way to learn something new, so let's go over more examples of using list comprehensions. They will illustrate how to transform and filter data efficiently.
Let's start with a bunch of numeric transformations inside of a list comprehension. We have a simple list of number 1-5, and now I want to create a list of squared, cubed number and even add some filtering.
Here is how I would do it:
💡Notice in the last example that I've added if/else
statement for returned value.
So, you can use if/else
in the end of your comprehension to filter items in the collection you iterate through, or you can use if/else
to decide on what value should be returned in your comprehension. You can even combine it, but let's not overcomplicate it.
Here is the syntax breakdown to help you understand it:
💡Notice in the last example that I've added if/else
statement for returned value.
So, you can use if/else
in the end of your comprehension to filter items in the collection you iterate through, or you can use if/else
to decide on what value should be returned in your comprehension. You can even combine it, but let's not overcomplicate it.
Here is the syntax breakdown to help you understand it:
List Comprehension - Simple Filtering
Alright, let's look at another example, and this is probably the most common case where you would use list comprehensions.
Let's say you have a list of data, and you want to create a new list by filtering something out. Let's keep it simple and filter only materials that contain a letter 's'
Here is how we would do that:
👆 Practice this one, because you will use it every time you need to create new list of data from existing one. Super useful!
Dictionary Comprehensions
Lastly, I want to show you that we can use exactly the same logic to create dictionary comprehensions.
As you remember, dictionaries need 2 things:
Key
Value
And we can use exactly the same syntax used in list comprehensions, but we need to make sure that we return both Key
and Value
separated by a colon :
.
Here is a simple example where we will make keys lowercase and values uppercase.
This technique is extremely useful in Revit API, where you often need to map object names to their corresponding objects. At least that's how I prefer to do it, and I will show you examples in the next module.
Summary: Why Use Comprehensions?
I think we can agree that when we use comprehensions, our code looks much cleaner and easier to read. It might look a bit hard in the beginning when you are unfamiliar with the syntax. But once you know the rules, it gets easier than traditional way.
So I highly recommend you to use comprehensions so your code becomes:
More Readable
Takes Less Space
Often Faster Execution
However, don’t overuse them for complex conditions. When you need to go through many steps, or create very long statements - it's best to stay with the usual way to provide better clarity. But you will develop your own preference over time when use one method over another.
HomeWork
Follow along the lesson and try out the same examples that I provided you. Also, make sure to experiment and make your own changes.
Don't be afraid to try something new and go outside of comfort zone. It's good that you are watching me do it for you, but you will learn x10 times more if you just try to do something on your own.
Experiment and keep it simple and fun. You will be surprised how much quicker you understand this concept.
⌨️ Happy Coding!