Python List Comprehension Simplified

Python List Comprehension Simplified
In: Python NetDevOps

'Python List Comprehension' is a concise way to create a list. It is a single line of code that can replace a loop, making your code more pythonic and easier to read. List comprehension allows you to create a list by iterating over an iterable object, such as a list, tuple, or string, and applying an operation to each element. In this blog post, we will dive into the basics of list comprehension and explore how it can be used to improve your coding style.

Overview

When I started working with Python, my typical workflow to create a new list from the values of an existing list would look like the following.

  1. An existing list exists
  2. Create a new empty list
  3. Use a for loop and append method to add 'some' items from the existing list to the new list.
numbers = [1,3,4,7,9,12,15,20,21,26]
even_numbers = []

for number in numbers:
    if number % 2 == 0: # even numbers are exactly divisible by 2 that means remainder will be 0
        even_numbers.append(number)

print(even_numbers)

#output
[4, 12, 20, 26]

Python Modulo Operator % returns the remainder of dividing the left-hand operand by the right-hand operand. It's used to get the remainder of a division. So, 10 % 3 would give the result of 1

List Comprehension

If I were to re-write the same code in the Pythonic way using list comprehension,  it would look like the following. You can do all the for loop and conditionals with just one line of code.

numbers = [1,3,4,7,9,12,15,20,21,26]
even_numbers = [number for number in numbers if number %2 == 0]

print(even_numbers)

#output
[4, 12, 20, 26]
💡
Pythonic describes a coding style that leverages Python's unique features to write code that is readable and beautiful

Syntax

newlist = [expression for item in iterable if condition == True]

Multiple Conditions

Let's look at another example with multiple conditionals. Let's say we want to find all the colours that have the letters a and o in them but not the letter l

The code would look like the following where we can group all the conditionals inside a parenthesis.

colours = ['red', 'blue', 'green', 'yello', 'purple', 'orange']
specific_colour = [colour for colour in colours if ('a' and 'o' in colour and 'l' not in colour)]

print(specific_colour)

#output
['orange']

Closing Thoughts

Thank you for reading my blog post on 'Python List Comprehension' and I hope you found the information useful and that it gave you some new insights or ideas to consider.

If you have any thoughts or questions about the topic, please feel free to leave a comment or send me a message. I would love to continue the discussion and hear your perspective. Again, thank you for taking the time to read my post and for supporting my writing.

Table of Contents
Written by
Suresh Vina
Tech enthusiast sharing Networking, Cloud & Automation insights. Join me in a welcoming space to learn & grow with simplicity and practicality.
Comments
More from Packetswitch
Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to Packetswitch.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.