Python Tricks: List Comprehensions | Use list comprehension to replace your stupid for-loop and if-else statement.
A Pythonic way to write a python list.
Why I am writing this article?
List comprehensions provide a concise way to create lists. Python makes its syntax very powerful that even a list can do a lot of things, can replace for loop and if else in some situations. However most people don’t know how to use it, or they are just satisfied with for loop and if-else and don’t even try to learn it.
The truth is, if you do not know how to write Pathonic code, you should never say you know python😱.
The most authority tutorial is the python doc. https://docs.python.org/3/tutorial/datastructures.html#tut-listcomps
But it is short, and not as readable as my article ( I insert pics ).
Let’s go figure it out with some examples:
Example 1: convert a for loop & if statement with a list
The first example is that given a list of numbers, and you need to write something to make it return a list of the number*2 for each odd number in the list given.
For the most straightforward solution, I think everyone can write a function as I wrote below:
number = [1,2,3,4]
output = []
for i in numbers:
if i%2 == 1:
output.append(i*2)
Then let’s write a list to get the result directly:
output = [i*2 for i in numbers if i%2 ==1 ]
The .gif below makes it very easy to understand the process to convert a for-loop and if-statement into a list comprehension.
Example2: compare two list
What about given two list A, B and you need to output the numbers only in list A.
There are of course lots of solutions for this question, you can use
ans = set(A) -set(B)
and you can use for loop to compare every number in both list, like this:
ans = []
for i in A:
if i not in B:
ans.append(i)
But let’s do it with just a simple list:
ans = [i for i in A if i not in B]
Example3: convert for loop and if-else statement into a list.
This is an assignment of MIT 6.00.1 python programming.
Write a function getGuessedWord
that takes in two parameters - a string, secretWord
and a list of letters, lettersGuessed
. This function returns a string that is comprised of letters and underscores, based on what letters in lettersGuessed
are in secretWord
. This shouldn't be too different from isWordGuessed
!
Example Usage:
>>> secretWord = 'apple'
>>> lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
>>> print(getGuessedWord(secretWord, lettersGuessed))
'_ pp_ e'
In the first glance of this question, you might write some code as I wrote below:
def getGuessedWord(secretWord, lettersGuessed):
lenth = len(secretWord)
point = 0
out = []
while point < lenth:
if secretWord[point] in lettersGuessed:
out.append(secretWord[point])
else:
out.append(' _')
point += 1
return str(''.join(out))
But if you know how to leverage the power of list comprehension, you can do it this way:
def getGuessedWord(secretWord, lettersGuessed):
return ''.join([i if i in lettersGuessed else '_ ' for i in secretWord ])
Notice: if you are going to use the if-else statement in the list comprehension, you must put the for-loop at the end of your code.
if you write like this:
[i for i in list if conditionA else 'string'] you will get an error.
In general, you should write list comprehension as below.
[f(x) if condition else g(x) for x in sequence]
Let’s do a quick review of what we got so far.
- if convert a for-loop and if statement into list comprehension:
- Must put the for loop in the beginning: [i for i in lista if i not in listb]
- You’ll definitely get an error if you put the for loop in the end, like this[ i if i in lista not in listb for i in lista]
- If convert a for-loop and if-else statement in list comprehension:
- Must put the for loop in the end[ i if i not in listb else 0 for i in lista]
- You’ll definitely get an error if you put the for loop in the end, like this[ [i for i in list if conditionA else ‘string’]]
Thank you for reading this article, I believe that you should understand the list comprehension in python, and I believe you already can use it in your code. But if you still need more examples, please refer to