Tips for Python List Comprehensions
List Comprehensions¶
These are useful Python constructs of the form:
[expression
for item
in iterable
(if condition
) ]
and will return a new list.
They have a number of uses and can make code much neater (and more understandable IF you understand them). We'll look at some use-cases by example. This is based on a Medium post by Yang Zhou.
As a for-loop¶
txt = 'Betelgeuse is a Red Giant star'
chars = [char for char in txt]
print(chars)
my_array = [[ 1,3,515,2],
[-1,66,4,99],
[199,3,4,5]]
max_in_row = [max(row) for row in my_array]
print(max_in_row)
Using an if statement¶
names = ['Tom', 'Dick', 'harry', 'Jill', 'fred', 'Freda', 'foxtrot']
print([name for name in names if name.startswith('F')])
print([name for name in names if name.capitalize().startswith('F')])
print([name for name in names if len(name) > 4])
print([name for name in names if len(name) > 4 and name.islower()])
More complex expressions¶
names = ['Tom', 'Dick', 'harry', 'Jill', 'fred', 'Freda', 'foxtrot']
print([name.capitalize() for name in names])
print([name if name.capitalize().startswith('F') else 'Not F' for name in names])
Applying a function to a list - alternative to map()¶
def calc_radial_vel(f_delta):
c = 2.99979e8
f0 = 1420e6
return (-c*f_delta/(f_delta+f0))
f_deltas=[-800000, -400000, 0, 200000, 600000]
radial_vels =[calc_radial_vel(v) for v in f_deltas]
print(f'Radial velocities are: {radial_vels} km/s')
Or, how about this neat way of printing out a list? (The [None, None, None, None] is an 'artifact' of Jupyter Notebook printing out the last result (4 print()s returning 'None')
[print(f'Velocities {a/1000:0.1f} km/s') for a in radial_vels]

Made in RapidWeaver