Python-12

/

/

/

python/12-list-comprehensions

Python Comprehensions: The Art of Writing Clean and Efficient Code

We are getting to the end, and I want to introduce you to one of my favorite concepts in python - comprehensions. They are considered a bit of an advanced topic, but we won't go crazy, and they are actually very simple once you use it a few times.

Python-12

/

/

/

python/12-list-comprehensions

Python Comprehensions: The Art of Writing Clean and Efficient Code

We are getting to the end, and I want to introduce you to one of my favorite concepts in python - comprehensions. They are considered a bit of an advanced topic, but we won't go crazy, and they are actually very simple once you use it a few times.

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

toggle = False
if toggle:
    word = 'Enabled'
else:
    word = 'Disabled'
print(word)

Now, let's rewrite this with exactly the same result but using if statement comprehension:

word = 'Enabled' if toggle else 'Disabled'
print(word)

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

items = ['item_a', 'item_b', 'item_c']

# Traditional way
upper_items = []
for item in items:
    item_upper = item.upper()
    upper_items.append(item_upper)

print(upper_items)

And now let me use List Comprehensions to achieve exactly the same result

items = ['item_a', 'item_b', 'item_c']

# Using list comprehension
upper_items = [item.upper() for item in items]

print(upper_items)

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:

items = ['item_a', 'item_b', 'item_c', 'wrong_data']
# Traditional way
upper_items = []
for item in items:
    if 'item_' in item:
        item_upper = item.upper()
        upper_items.append(item_upper)

And now the same thing, but with list comprehension:

items = ['item_a', 'item_b', 'item_c', 'wrong_data']

# Using list comprehension
upper_items = [item.upper() for item in items if 'item_' in item]
print(upper_items)

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:

numbers       = [1, 2, 3, 4, 5]
num_sq        = [num**2 for num in numbers]  # Squared numbers
num_cube      = [num**3 for num in numbers]  # Cubed numbers
num_cube_even = [num**3 for num in numbers if num % 2 == 0]  # Cubes of even numbers
even_odd      = ['Even' if num % 2 == 0 else 'Odd' for num in numbers]  # Even/Odd classification

print(num_sq)
print(num_cube)
print(num_cube_even)
print(even_odd)

💡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:

mats = ["wood", "steel", "concrete", "bricks", "glass", "plaster"]
mats = [mat for mat in mats if 'w' in mat]  # Only materials containing 's'
print(mats)

👆 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.

mats = ["wood", "steel", "concrete", "bricks", "glass", "plaster"]
dict_mats = {mat.lower(): mat.upper() for mat in mats}  # Lowercase keys, uppercase values
print(dict_mats)

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:

  1. More Readable

  2. Takes Less Space

  3. 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!

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API