Python List Inference

In Python, List derivation is a concise syntax that makes it easy to create lists. The syntax format for list derivation is:

[expression for item in iterable if condition]

Among them:

  • expression: is an expression used to calculate the value of each element.
  • item: is a variable that represents each element in iterable.
  • iterable: It is an iterable object that can be a list, tuple, set, dictionary, etc.
  • condition: is an optional conditional expression used to filter elements.

For example, a list derivation can be used to create a list containing squares from 1 to 10:

squares = [i**2 for i in range(1, 11)]
print(squares) #output :[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Here, the list derivation formula [i**2 for i in range(1, 11)] represents calculating the value of i**2 for each element i in range(1, 11) and adding this value to the list.

Conditional expressions can also be added to filter elements, such as:

even_squares = [i**2 for i in range(1, 11) if i % 2 == 0]
print(even_squares) #output :[4, 16, 36, 64, 100]

Here, the conditional expression if i % 2 == 0 indicates that the value of i**2 is only calculated and added to the list when i is even.

List derivations can be nested, for example, two nested list derivations can be used to create a two-dimensional matrix:

matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix) #output :[[1, 2, 3], [2, 4, 6], [3, 6, 9]]

Here, [[i * j for j in range(1, 4)] for i in range(1, 4)] represents the use of two nested list derivations. For each element i in range(1, 4) and each element j in range(1, 4), calculate the value of i*j and add this value to the corresponding position in the matrix.

Related articles