Python List Comprehension: With Examples

Python List Comprehension: With Examples

by Alex Hyett | 2 min read

Working with arrays can be a bit of a pain in most languages.

If you want to make changes to an array you need to use a FOR loop, a bit like this one:

fruits = ["apple", "banana", "grape", "mango", "pear", "raspberry"]
new_fruits = []

for x in fruits:
  new_fruits.append(x + "s")

print(new_fruits)

All we wanted to do was add an “s” to the end of each of the words in the array but to do that we had to create a new array and then a loop to add the letter to each of the words.

Replacing FOR Loops with List Comprehension

Thanks to the power of List Comprehension in Python, there is a much better way of doing this, which will save you a lot of time and code.

fruits = ["apple", "banana", "grape", "mango", "pear", "raspberry"]
fruits = [fruit + "s" for fruit in fruits]
print(fruits)

The second line contains the Python List Expression which is doing exactly the same thing as the previous example.

We no longer need a new array as we can just overwrite the previous array.

If you want to create your own Python List Expressions then you can use the following formula.

new_list = [expression for item in array if condition == True]

Using Conditionals in List Comprehension

You can see in the formula above that we can also use conditionals in our expressions.

Let’s say we are upset by the fact that “raspberrys” isn’t actually a word. We can add a conditional to a statement that will filter this word out.

fruits = ["apple", "banana", "grape", "mango", "pear", "raspberry"]
fruits = [fruit + "s" for fruit in fruits if fruit != "raspberry"]
print(fruits)

We can also include conditionals at the start if we want to replace certain entries:

fruits = ["apple", "banana", "grape", "mango", "pear", "raspberry"]
fruits = ["raspberries" if fruit == "raspberry" else fruit + "s" for fruit in fruits]
print(fruits)

String Manipulation

Given that strings are nothing more than character arrays we can also use List Comprehension to manipulate text.

Say for example we had the following piece of text and we wanted to add the spaces back in:

ILikeSpellingFruitPluralsIncorrectly

Normally we would need to loop through each letter looking to see if it is upper case or not and add in a space.

text = "ILikeSpellingFruitPluralsIncorrectly"

text = "".join(
	[ i if i.islower() else " " + i for i in text ]
)[1:]
print(text)

Which prints out: I Like Spelling Fruit Plurals Incorrectly

Final Thoughts

List Comprehension is a powerful way of doing simple FOR loops and array manipulations without needing to write a lot of code.

As Uncle Ben said to Peter Parker, “With great power comes great responsibility”. List Comprehension is great for simple expressions to make your code cleaner, but take caution if you are writing complicated loops in this way.

Even if it takes a few more lines of code, it is always better that your code is easier to understand than concise.

Was this helpful?
If you need more help, I also have a private Discord community for my fans where they can ask me questions. As a fan, your name is included at the end of my YouTube videos as well getting exclusive content and discounts to my future courses.
🌟 Find out more about becoming a Fan
Or you could buy me a coffee ☕️ to say thank you, any support is appreciated.


ALSO ON ALEXHYETT.COM

Finally Understand Regular Expressions: Regex isn't as hard as it looks

Finally Understand Regular Expressions: Regex isn't as hard as it looks

  • 10 January 2023
There’s nothing like a regular expression to strike fear in the heart of a developer. Regular expressions (regex) are used for a lot of…
How I would learn to code (if I could start over)

How I would learn to code (if I could start over)

  • 06 January 2023
When I was 8 years old I learnt how to code. I learnt to code from an old BASIC book that my Dad had lying around from his ZX Spectrum. I…
Understanding Big-O Notation

Understanding Big-O Notation

  • 03 January 2023
It’s important when you’re writing applications especially, those that are going to be processing a large amount of data that you understand…
Stack vs Heap Memory - What are the differences?

Stack vs Heap Memory - What are the differences?

  • 30 November 2022
In modern programming languages such as C# or Java, we tend to take memory management for granted. Gone are the days when we need to call…
Git Flow vs GitHub Flow

Git Flow vs GitHub Flow

  • 10 November 2022
Losing code that you have spent hours writing can be painful, which is why we use version control (or source control) to store our code and…
Bitwise Operators and WHY we use them

Bitwise Operators and WHY we use them

  • 26 October 2022
Bitwise operators are one of those concepts that a lot of programmers don’t understand. These are not used a great deal anymore so you can…
8 Data Structures you NEED to Know

8 Data Structures you NEED to Know

  • 26 October 2022
You can get pretty far in programming without understanding Data Structures, but eventually, you are going to need to know them, understand…
Binary Numbers Explained for Programmers

Binary Numbers Explained for Programmers

  • 21 October 2022
Everyone knows that computers run on ones and zeros. This is because CPUs are made up of billions of transistors, which are basically just…