List comprehensions in Python

This post is a part of my Python documentation, in case you are learning Python. In below coding examples I cover list comprehensions, a compact way of creating lists, allowing for filtering too.

# first example of a python list comprehension;
# syntax is list = [element from sequence (with filter)];
# below example does not apply a filter
a = [i for i in range(0,10)]
a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# another example, applying addition element-wise operation 
b = [i*10 for i in range(0,10)]
b
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
# example that uses a filter
c = [i for i in range(0,10) if i > 5] # filter syntax "if i > 5"
c
[6, 7, 8, 9]
# in python, we can iterate through strings
for i in "this is a string":
    print(i)
t
h
i
s
 
i
s
 
a
 
s
t
r
i
n
g
# an example of a lsit comprehension statement applying a filter to every character in a string
d = [int(i) for i in "string1with2some3numbers4in5it" if i.isnumeric()]
d
[1, 2, 3, 4, 5]
# in above example I converted every element into an integer; 
# if I do not do this, the list will be a list of strings;
# having a list of strings allows us to apply string methodes;
# in below example I do not convert into integers and use the .join method
e = "".jojoin([i for i in "string1with2some3numbers4in5it" if i.isnumeric()])
e
'12345'

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Close

Meta