Python – List Comprehensions

Basically, it produces a list but only once. That’s why it comes under or is associated with functional programming.

What is functional programming? It refers to computer programming using a “pipeline of pure functions”. (Héla Ben Khalfallah. 12 Jan 2021. Functional Programming, Simplified. https://betterprogramming.pub/simplified-functionaldd-programming-fdc07b4b1084).

What are functions? A function is a block of code that performs a specific task. (Parewa Labs Pvt. Ltd. Python Functions. https://www.programiz.com/python-programming/function. It “only runs when it is called”, so in this sense it offers more control to the software programmer. Once it runs, it’s gone (see Rodrigo Girão Serrão. 18 Jun 2022. List comprehensions in functional programming. https://mathspp.com/blog/twitter-threads/list-comprehensions-in-functional-programming). That is why some suggest functional programming makes your code more secure.

You will find below a modified replica of Christian Mayer’s example from Python One-Liners Write Concise, Eloquent Python Like a Professional (2020). https://github.com/finxter/PythonOneLiners/blob/master/book/python_tricks/one_liner_06.py.

# modified example: execute List Comprehension with Slicing

## Data (daily copper prices ($))
price = [[10.91, 9.8, 9.8, 9.4, 9.5, 9.72, 8.88],
[11.52, 9.4, 9.4, 9.3, 9.2, 9.13, 8.88],
[8.45, 7.9, 7.9, 8.1, 8.0, 8.0, 9.88],
[8.16, 5.9, 4.8, 4.8, 4.7, 3.99, 9.99],
[11.52, 9.4, 9.4, 9.3, 9.26, 9.13, 11.06]]

## creates smaller sample to run computer modelling with less time
## extracts every other datapoint from each sub-list
sample = [line[::2] for line in price]

## note that the output is a list! You find that it begins with a square bracket and ends with a square bracket.
print(sample)

[[10.91, 9.8, 9.5, 8.88], [11.52, 9.4, 9.2, 8.88], [8.45, 7.9, 8.0, 9.88], [8.16, 4.8, 4.7, 9.99], [11.52, 9.4, 9.26, 11.06]]

Hope it’s been fun for you!

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.