Skip to content

Network Automation

My journey with Network & Cloud Automation

Menu
  • Beginner
  • DevOps-NetDevOps
  • Network Automation
    • Docker
    • Python Libraries
      • NAPALM
      • Netmiko
      • Jinja2
      • Scrapli
      • Yang
  • Cloud Automation
    • Terraform
  • Python 🐍 Tips and Tricks
Menu
list comprehension

Python List Comprehensions

Posted on October 28, 2021October 26, 2021 by Gurpreet Kochar

From the perspective of a network engineer who has just started out on their journey to learn python and network automation, one of the first intimidating concepts that they are likely to come across is the list comprehensions. In this post we will try and cover the basics of python list comprehensions

If you have overcome the hurdle of understanding python’s conditional statements like for and if/else, the next step is to make the code concise at the cost of readability at first but gradually once you get hang of comprehensions, the readability isn’t that big of an issue.

Let’s take an example to take a look at the most common list comprehension generic patterns.

For loop containing single IF statement

devices = ['xxx-indi-ce01', 'xxx-indi-ce02', 'xxx-usam-ce01', 'xxx-usam-ce02', 'xxx-cana-ce01', 'xxx-cana-ce02', '', '', None]
device_list = []
for device in devices:
    if device:
        device_list.append(device)
# List comprehension equivalent of above
device_list = [device for device in device_list if device]

# Generic syntax
device_list = [append value in list for each value in list ifcondition=True]

For loops containing IF/ELSE Statements

devices = ['xxx-indi-ce01', 'xxx-indi-ce02', 'xxx-usam-ce01', 'xxx-usam-ce02', 'xxx-cana-ce01', 'xxx-cana-ce02', '', '', None]

device_list = []
for device in devices:
    if device:
        device_list.append(device)
    else:
        device_list.append('PLACEHOLDER')

print(device_list)
['xxx-indi-ce01', 'xxx-indi-ce02', 'xxx-usam-ce01', 'xxx-usam-ce02', 'xxx-cana-ce01', 'xxx-cana-ce02', 'PLACEHOLDER', 'PLACEHOLDER', 'PLACEHOLDER']
# List comprehension equivalent of above
device_list = [device if device else "PLACEHOLDER" for device in devices]

# Generic syntax
device_list = [append value ifcondition=True else append else block value for device in list]

For loops containing IF/ELIF/ELSE Statements

This one is a little tricky and there is an increased loss of readability. There is no elif keyword usage while using list comprehension, you could only use if and else. So the workaround is to break down elif into if and else.

devices = ['xxx-indi-ce01', 'xxx-indi-ce02', 'xxx-usam-ce01', 'xxx-usam-ce02', 'xxx-cana-ce01', 'xxx-cana-ce02', '', '', None]

device_list = []
for device in devices:
    if device:
        device_list.append(device)
    elif device == '':
        device_list.append('EMPTY')
    else:
        device_list.append('PLACEHOLDER')

print(device_list)
['xxx-indi-ce01', 'xxx-indi-ce02', 'xxx-usam-ce01', 'xxx-usam-ce02', 'xxx-cana-ce01', 'xxx-cana-ce02', 'EMPTY', 'EMPTY', 'PLACEHOLDER']
# List comprehension equivalent of above
device_list = [device if device else "EMPTY" if device == '' else "PLACEHOLDER" for device in devices]

# Generic syntax
device_list = [append value ifcondition=True else append '' if elif condition is True else append 'else value' for each value in list]

The list comprehension statement above will make much more sense if we breakdown elif into if and else like below

device_list = []
for device in devices:
    if device:
        device_list.append(device)
    else:
        if device == '':
            device_list.append('EMPTY')
        else:
            device_list.append('PLACEHOLDER')

print(device_list)

Multiple nested IF’s

device_list = []
for device in devices:
    if device:
        if 'indi' in device:
            device_list.append(device)

print(device_list)
['xxx-indi-ce01', 'xxx-indi-ce02']
device_list = [device for device in devices if device if 'indi' in device]

If you notice carefully, the syntax of list comprehension has if else statement ahead of “for device in devices” if we are dealing with if and else together. However if our reference code has only if statements, the if statements are followed after the “for device in devices” in comprehension. Following the same rule, multiple if statements are also handled after “for device in devices” and are just stacked together one after the other in sequence.

Above comprehension could also have been written as

device_list = [device for device in devices if device and 'indi' in device]
which is equivalent to
device_list = []
for device in devices:
    if device and 'indi' in device:
        device_list.append(device)

Conclusion:-

While list comprehensions make your code look beautiful it can come at the cost of lack of readability. As per Zen of python, clear is better than concise. Comprehension is something that one should use gradually and build upon as you use it more and more often. Secondly, after understanding the basic rules of comprehension, write complex comprehensions become relatively easier if you can breakdown the conventional for loop with nested if and else blocks into simpler if else heirarchy.

Know someone who may benefit? Share this:

  • Tweet
  • Click to share on Telegram (Opens in new window) Telegram
  • Click to share on WhatsApp (Opens in new window) WhatsApp
  • Click to email a link to a friend (Opens in new window) Email
  • More
  • Click to print (Opens in new window) Print
  • Click to share on Reddit (Opens in new window) Reddit
  • Share on Tumblr
  • Pocket

Like this:

Like Loading...

Related

Leave a ReplyCancel reply

All Blog Posts
My Resume

Upcoming Posts

Sorry - nothing planned yet!

Recent Posts

  • How to backup configuration to TFTP Server using Ansible – Part II
  • How to backup network devices using Ansible – Part I
  • Netmiko SSH Proxy/JumpServer
  • A short note on SASE
  • Understanding Ansible

Recent Comments

  1. Jack on Multithreading with Python for Network Engineers
  2. LifeCanvas on [Theory] Multithreading vs Multiprocessing vs AsyncIO
  3. Jasper Horng on Netmiko SSH Proxy/JumpServer
  4. asdfasdf on Python API Using FASTAPI – UPDATE – PUT – PATCH – Part V
  5. Gurpreet Kochar on Python Scrapli AsyncIO Usage

Archives

  • September 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
Topic Request / Suggestion
Loading
© 2025 Network Automation | Powered by Minimalist Blog WordPress Theme
 

Loading Comments...
 

    %d