List comprehension

from Wikipedia, the free encyclopedia

List comprehensions or list abstractions are syntactic structures that describe how existing lists or other iterable objects are processed in order to create new lists from them.

They are written in some programming languages ​​such as B. Python , Haskell , or Common Lisp supported and in analogy to descriptive set notation (Engl. Set-builder notation ) stock exchanges.

Similarities to the notation of sets

The set of square numbers with even bases between 10 and 20 can be noted using the descriptive set notation as follows

.

In Haskell, a list comprehension that meets the same conditions looks like this:

m = [x^2 | x <-[10..20], mod x 2 == 0)]

Note that the specification [10..20] implicitly indicates that a subset of the natural numbers is in the input set.

The following notation is used in Python

m = [x**2 for x in range(10,21) if x%2 == 0]

Almost the same applies here as with Haskell, except that when the range class is initialized, 1 must be added for the upper limit.

All three notations can be broken down into four parts:

  • Output expression ( output expression ): x ^ 2
  • Variable: x
  • Input set : the natural numbers N
  • Predicate / property ( predicate ): the even numbers of the input set

Multi-dimensional fields

Some programming languages ​​like Python or Haskell do not have native support for multidimensional fields. In such a case, you can use List Comprehensions to create a replacement design.

This example creates an empty 5x5 matrix substitute construction with lists:

m = [[None for zeile in range(5)] for spaltenNr in range(5)] # Erstellung
m[1][4] = 4 # Element in Zeile 2, Spalte 5 mit dem Wert 4 belegen

The output expression is also a list comprehension. So it is a matter of nesting.

The inner List Comprehension creates a row of five elements with the null value None and the outer List Comprehension then ensures that a list with five rows is created unconditionally (without a predicate). The access then works like a normal multidimensional field.

Individual evidence

  1. Python Tutorial: List Comprehension
  2. Built-in Types - Python 3.7.1 documentation