Small Talk

Small Talk

Python List Comprehension - Easy Swipe Template Included!

My first taste of coding began with vanilla Javascript. After mastering it somewhat, I came to the humble conclusion that if I were to write a coding language myself, I'd do it waayy better.

It would literally be like English.

But then I was introduced to Python and, apparently, someone had once had the same idea that I had and went and wrote a language that reads like English (well, almost) and also has methods for all of the processes that take 770 lines of code in Javascript.

I am now going to demonstrate the superiority of Python over Javascript with one specific example: List Comprehension.

The Situation

Imagine you have a list of ice cream flavors that users can view when ordering.

You want to transform each flavor into title-case, except Vanilla, which needs to be in all caps to give it a chance to get noticed.

And, sadly for many, peanut butter must be excluded due to allergies.

Simple enough?

Plain English

Let's break this down in plain English:

List of Ice Cream Flavors:

  • vanilla

  • chocolate

  • pistachio

  • strawberry

  • caramel

  • raspberry

  • peanut butter

Create a new list with these flavors except for peanut butter. They should all be converted to title case, except for vanilla, which should be in all caps.

Javascript

Here is that operation in Javascript:

const modifiedFlavors = [];

for (let i = 0; i < iceCreamFlavors.length; i++) {
    const flavor = iceCreamFlavors[i].toLowerCase();

    if (flavor === 'vanilla') {
        modifiedFlavors.push('VANILLA');
    } else if (flavor !== 'peanut butter') {
        modifiedFlavors.push(flavor.charAt(0).toUpperCase() + flavor.slice(1));
    }
}

console.log(modifiedFlavors);

I mean, you couldn't have found a better way?

There are so many steps here. And what happens if the flavor has two words?! Let's not even go there.

And yes, while you could use maps and filter, I personally find that to be even less readable.

Put simply, this code is very, very, codey.

Python

Step aside, JavaScript. Enter Python's unbearably delicious List Comprehension:

modified_flavors = [
    'VANILLA' if flavor == 'vanilla' else flavor.title()
    for flavor in ice_cream_flavors
    if flavor != 'peanut butter'
]

print(modified_flavors)

I mean, just look at that.

Look how short it is.

Look how readable it is!

Make it "VANILLA" if it's vanilla, otherwise make it title-case (with our lovely built in method, mind you), for every single flavor in the list, but only if it's not peanut butter.

Done.

Do you want to know how to do it, too?

Of course you do. I will now show you how.

List Comprehension Formulae

Here's a quick reference guide for iterating through lists and return a new list with (or without) modification:

  • Iterate through an entire list without modifying it:

      new_list = [expression for item in iterable]
    
  • Get a list of only the items that meet a certain condition:

      new_list = [expression for item in iterable if condition is True]
    
  • Modify all the items in some way:

      new_list = [expression for item in iterable]
    
  • Replace the items that meet a certain condition:

      new_list = [other_item if condition is True else expression for item in iterable]
    
  • All together now! Modify some items, replace others, but all this only for items that meet a certain condition:

      new_list = [other_item if condition is True else expression for item in iterable if condition is True]
    

Take a moment to appreciate how your life has now changed.

Delicious! 🍦✨