List Comprehension in Python

This is a guide on list comprehension in Python
 

Check out Audible on Amazon and listen to the newest books!

 
 
List comprehension is a way of creating lists in python. It is a smart way of
creating lists and I know you will like it. Here is an example:
 
[x*3 for x in range(10)]
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
 
The variable "x" start at zero and goes up by 1 each time. Each x is multiplied
by 3. The range function gives you 10 values. The expression can be more complex
if you need it to. It can be a function, do calculations, and also call other
functions. 
 
print([x for x in range(10))]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
In this next example we change it up a little bit. Hopefully you can see how
this works and why. It is really neat. The variables "x" becomes the values
0-4(because range(5)) and them multiples each value by 4 and prints it.
 
print([x*4 for x in range(5)])
[0, 4, 8, 12, 16]
 
We can make it more complex and do more at once.
print([(a,b) for a in range(5) for b in range(5)])
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]
 
The variable "a" iterates over each value of "range(5)". The variable "b" does
the same thing. Each combination is then printed.
 
Here is another expression where we square a number.
print([x**2 for x in range(30) if x % 2 > 0])
[1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625, 729, 841]
 
The variable "x" iterated over each value returned by the "range()" function.
The variable "x" is then squared for each value. 
 
The next example analyzes text. We will just do something simple to show one of
the possibilities. We put everything in triple quotes. This text is from a
Pokemon card. It looks at all the words and gets rid of anything 3 chars or
less. Then we print that to the screen.
 
text = '''
Discard the top card of your deck, and if that card is a Pokemon that does not have a rule box, choose 1 of its attacks and use it as this attack.
'''
w = [[x for x in line.split() if len(x) > 3] for line in text.split('\n')]
print(w)
[[], ['Discard', 'card', 'your', 'deck,', 'that', 'card', 'Pokemon', 'that', 'does', 'have', 'rule', 'box,', 'choose', 'attacks', 'this', 'attack.'], []]
 
Reading a file is another common task. There are several ways to do so. This is
just one way. I will leave it to you to decide which is the best way. In this
example, we read all the lines in a file, get rid of white space characters, and
put the result in a list. Adjust your filename to whatever file you are using.
This file must be in system path, same directory, or you must state the explicit
path. I did this this in IDLE from my Linux system.
 
print([line.strip() for line in open("slowking.py")])
 
In this next example, we analyze a list of strings. It could be something we
type in or reading from a text file, like we did earlier. We are looking for a
certain sub-string called "Pokemon" from the list of string we provide. We have
a Boolean indicate whether each string that is analyzed contains the sub-string
we are looking for.
 
slowking = ['Discard the top card of your deck.',
            'If that card is a Pokemon.',
            'Choose one of its attacks and use it.']
pokemon = map(lambda a: (True, a) if 'Pokemon' in a else (False, a), slowking)
print(list(pokemon))
 
[(False, 'Discard the top card of your deck.'), (True, 'If that card is a Pokemon.'), (False, 'Choose one of its attacks and use it.')]
 
Our next topic is slicing. This is important when analyzing string data. When we
want to search for specific text or a string, slicing will get that data for us.
Slicing gets you part of a string. It looks like this:
 
x[start:stop:step]
 
Start and stop should be obvious. The step part is optional. If you do not
include it then the default step is 1. Remember the first element is index 0. If
you do not include the stop or stop position then python goes from the start to
the end. 
 
s = 'seek inspiration'
print(s[0:4])
seek
 
print(s[3:])
k inspiration
 
print(s[:5])
seek 
 
print(s[5:])
inspiration
 
print(s[:100])
seek inspiration
 
In this next example we are trying to find a specific sequence of
characters. 
 
slowking ='''Discard the top card of your deck. If that card is a pokemon that does not have a rule box, choose one of 
its attack as this attack. Pokemon EX have rule boxes. Super psybolt is 120.'''
find = lambda x, q: x[x.find(q)-10:x.find(q)+10] if q in x else -1
print(find(slowking,'Pokemon'))
 
Given a large set of numbers, we might want to break it down some to make it
easier to work with. We can attempt this by using a step 2 when we slice to
cut it in half. Then we want to print what we have. Let us consider some batting
averages of the top players in the current 2025 season.
 
ba = [[.384, .369, .338, .329, .328, .322],
      [.318, .317, .316, .312, .310, .310],
      [.309, .304, .304, .302, .300, .299],
      [.299, .299, .299, .297, .296, .296]]
half = [line[::2] for line in ba]
print(half)
[[0.384, 0.338, 0.328], [0.318, 0.316, 0.31], [0.309, 0.304, 0.3], [0.299, 0.299, 0.296]]
 
Sometimes you are given a list of numbers and you need to graph them. There are
many ways to do this but the first you should learn is the matplotlib library.
First, we need to install it.
 
pip install matplotlib
 
Now, let us work with some data. You can copy/paste or use some other method.
This is just an example so I will leave that part to you. Later on, I will do a
dedicated section on matplotlib. Here is how you work with it on a basic level.
 
import matplotlib.pyplot as plt
integers = [1,2,3,2,4,5,3,6,7,4,7,8,5,8,9,6,2,1,3,3,2,4,5,4,3,7,6,6]
plt.plot(integers)
plt.show()
 
First, we import the matplotlib library. We then create an integer variable.
Last, we load the variable and show the plot.
 
The last thing we will do is learn how to combine lists. We do this by using the
'zip()' function.
 
list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = [11,12,13,14,15,16,17,18,19,20]
combined = list(zip(list1, list2))
print(combined)
 
[(1,11), (2,12), (3,13), (4,14), (5,15), (6,16), (7,17), (8,18), (9,19), (10,20)]