avatarDeck451

Summary

The web content provides an in-depth guide on enhancing Python coding skills through the use of list comprehensions, emphasizing their advantages in simplifying code and improving performance.

Abstract

The article titled "Up Your Python Coding Skills: List Comprehensions" delves into the utility and efficiency of list comprehensions in Python. It contrasts the traditional for loop with list comprehensions, demonstrating how the latter can create lists in a more concise and readable manner. The author argues that list comprehensions can lead to faster execution times, especially with large iterators, and eliminate the need for pre-initialized lists. While acknowledging the power of list comprehensions, the author also points out their limitations, such as the inability to include comments within the condition or to use break and continue statements. The article further explores advanced list comprehension techniques, including multiple conditions and if-else statements, and compares these to their equivalent for loop structures. The author, Deck, aims to help Python programmers refine their skills and maintain clean, maintainable code by mastering list comprehensions, which can also pave the way for understanding other types of comprehensions in Python.

Opinions

  • The author believes that list comprehensions are a more elegant alternative to traditional for loops.
  • List comprehensions are considered to potentially offer faster performance for certain operations.
  • The article suggests that list comprehensions improve code readability, as long as they are not made overly complex.
  • The author indicates that list comprehensions are limited in their flexibility compared to for loops, due to the absence of features like comments inside conditions, and control flow statements such as break and continue.
  • Deck posits that mastering list comprehensions is crucial for understanding other comprehension types in Python and for enhancing overall coding proficiency.

Up Your Python Coding Skills: List Comprehensions

Photo by Michael Dziedzic on Unsplash

Comprehensions in Python are thought (and rightly so, might I add) to be a more elegant (and sometimes even faster) alternative to the more traditional for loops we’re so used to, no matter what programming language we may study.

Out of the four known types of comprehensions (list, dictionary, set, and generator comprehensions), we’ll be focusing on the simplest of all: the list comprehension and we’ll see what it has to offer us.

List comprehension is a very useful concept in Python that allows for a more compact, elegant, and sometimes even easier to read code and, as its name suggests, focuses on creating a list out of an iterator’s elements.

Of course, we could spend all day talking theory, but more often than not, a simple practical example is something two hours’ worth of talking around the subject doesn’t come close to.

So, let’s consider, as a simple demonstration, that we’re given a list of digits (0 through 9) and that we’re asked to create another list that should only contain the even digits. We can do this very easily using a traditional for loop:

digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
even_digits = []
for digit in digits:
    if digit % 2 == 0:
        even_digits.append(digit)
print(even_digits)
Output:
[0, 2, 4, 6, 8]

Fairly simple and straightforward. Now let’s try a list comprehension:

digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
odd_digits = [i for i in digits if i % 2 == 1]
print(odd_digits)
Output:
[1, 3, 5, 7, 9]

The list comprehension is typically defined by the following rule, or, more specifically, matches the following pattern:

new_list = [ item for item in iterator if condition_is_true ]

We can pull some advantages to using list comprehensions straight away:

  • Firstly, they simplify the code. Always better to have the same result achieved in fewer lines of code — provided code readability isn’t affected by it;
  • Next, depending on what the evaluated condition contains (in terms of operands — the modulo or division operators are pretty computationally expensive) and depending on the size of the iterator, they can also be faster than a traditional for loop;
  • Also, it can be noted that, while the first example (the traditional for loop example) was appending to an already initialized empty list, the list comprehension doesn’t need an already initialize empty list: the construction of the list object and the populating of the list both get done during the evaluation of that simple one-liner.

A real code simplifier, provided it is easy to read. This is, more often than not, a subjective thing, but there is such a thing as a too complex list comprehension, so the trick here is to not overdo it, since it has its own limitations:

  • You can’t comment the condition you’re evaluating. You can only add comments before or after the entire comprehension line. This is equivalent to being able to add comments only before or after the for loop, but not inside it. And this isn’t something you always want. If the code you’re going for would be unreadable without internal comments, it’s probably better to use the for loop;
  • You can’t break your way out of a list comprehension. Not even the continue statement that’s used for skipping certain iteration steps, saving precious processing time can’t be used with list comprehensions. You’re stuck with the code going through each and every item of that iterator until it finishes processing all of them. So, while your for loop certainly allows for fancy stuff like the aforementioned break, or continue, this isn’t a privilege shared by list comprehensions.

There’s a bit more to what we can do with list comprehensions. The previous example I just shared has merely presented the standard form of a list comprehension:

new_list = [ item for item in iterator if condition_is_true ]

However, in practice, we may need to add some tweaks to this form to achieve what we’re going for, like, say, a multiple condition:

divisible_by_6 = [i for i in range(20) if i % 2 == 0 and i % 3 == 0]
print(divisible_by_6)
Output:
[0, 6, 12, 18]

The same effect can be achieved by nesting those if statements instead of writing a composite if statement:

divisible_by_6 = [i for i in range(20) if i % 2 == 0 if i % 3 == 0]
print(divisible_by_6)
Output:
[0, 6, 12, 18]

Also, what if we’re asked to create a list of results, based on each element’s parity? We’re going to need an if-else list comprehension:

digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
odd_or_even = ["Odd" if i % 2 == 1 else "Even" for i in digits]
print(odd_or_even)
Output:
['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']

Notice how this time around we placed the if condition ahead of the for statement? Let’s make things even more clear by complicating the matters for a bit: let’s say we want to obtain a list with the parity of positive elements, for a list of numbers ranging from -10 to 10, inclusively:

numbers = range(-10, 11)
out = ["Odd" if i % 2 == 1 else "Even" for i in numbers if i >= 0]
print(out)
Output:
['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']

This could be translated into the following for loop, that would achieve the same result:

numbers = range(-10, 11)
out = []
for i in numbers:
    if i >= 0:
        if i % 2 == 1:
            out.append("Odd")
        else:
            out.append("Even")
print(out)
Output:
['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']

The appending part could be compacted even more using ternary operators, or, as they’re more widely known in the Python community, conditional expressions.

numbers = range(-10, 11)
out = []
for i in numbers:
    if i >= 0:
        out.append("Odd" if i % 2 == 1 else "Even")
print(out)
Output:
['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']

The result is the same, but it’s easier to use this example to compare a for loop to its list comprehension equivalent.

Mastering the list comprehension technique will be a great help in understanding other types of comprehensions, like set, dictionary or generator comprehensions, that behave very similarly.

It will also help a great deal in keeping your code compact and elegant, yet still readable and easy to maintain. A truly awesome tool at your disposal, the list comprehension —and just about any type of comprehension in general — is a great way to really step up your game when it comes to coding in Python.

Time to wrap this one up. I’ll see you at the next one and until then, stay safe and happy coding!

Deck is a software engineer, mentor, writer, and sometimes even a teacher. With 12+ years of experience in software engineering, he is now a real advocate of the Python programming language while his passion is helping people sharpen their Python — and programming in general — skills. You can reach Deck on Linkedin, Facebook, Twitter, and Discord: Deck451#6188, as well as follow his writing here on Medium.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Check out our Community Discord and join our Talent Collective.

Python
Programming
Coding
Tutorial
List Comprehension
Recommended from ReadMedium
avatarJYOTI PRAKASH DEY
14 pandas tricks you MUST know

7 min read