List Generator

by Alex
List Generator

List generators in the Python programming language are powerful tools for working with diverse sets of data. Most often these constructs are used to interact with lists more conveniently, providing not only their creation, but also their modification. Despite the fact that in some cases you can do without generators, their competent use significantly simplifies the implementation of complex algorithms.

Simple generation

The simplest way to create a list is to assign to it the necessary values or objects. If there are few elements in the sequence, you can simply list them one by one. But if their number exceeds a dozen, you should seriously think about using a list generator. This design provides its automatic filling, based on certain instructions. The following example shows how Python creates a list of numbers using a generator. The variable i is a reference to the current item in the data object. The range function here takes two arguments that set boundaries for the generated sequence of integers. The output is done via the print method.

>>> data = [i for i in range(0, 10)]
>>> print(data)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Python 3 list generators work with more than just numeric values. As the following example shows, you can pass a string or a reference to a string as an argument to the generator.

>>> data = [i for i in "python"]
>>> print(data)
['p', 'y', 't', 'h', 'o', 'n']

The result of executing this code will be a list of characters that included the original string. As in the case with the previous example, you can print the resulting set of data to the screen using the already known print method.

Conditional generator

One of the frequently used ways of generating lists in Python is with a condition. The previous examples showed a fairly trivial approach to populating a list using a generator. These Python language constructs allow you to set certain conditions to perform such an operation. For example, there is the task of moving only even-numbered values from a previously created range sample into the list.

>>> data = [i for i in range(0, 10) if i % 2 == 0]
>>> print(data)
[0, 2, 4, 6, 8]

The if command comes into play, followed by a small instruction telling you that each element in the sequence must fulfill some condition. In this case, it is necessary to return 0 as a result of calculating the remainder of an integer division. As you can see, the checked digits have been put in the list.

Generator with a loop

In Python it is also possible to generate a list by using several loops and placing them in square initialization brackets. The following example uses two for constructs that alternately loop through the values for variables i and j. The numerical range for them (from 0 to 3) is specified through the range methods as before.

>>> data = [i * j for i in range(0, 3) for j in range(0, 3)]
>>> print(data)
[0, 0, 0, 0, 1, 2, 0, 2, 4]

The result of this code is a list of data, based on the alternate multiplication of the i and j variables. Thanks to the for loops, their values are incremented step by step. Thus, a list of nine elements is generated.

Generation of nested lists

Sometimes a programmer needs to use lists with more than one dimension. For example, multidimensional datasets may be needed when working with mathematical matrices. You can also use generators for this in Python by simply placing a loop to create one list inside another. The scope constraints for a nested list would be square brackets, as shown in the following example.

>>> data = [[i * j for i in range(0, 3)] for j in range(0, 3)]
>>> print(data)
[[0, 0, 0], [0, 1, 2], [0, 2, 4]]

This code demonstrates the creation of a two-dimensional 3×3 matrix using the Python two-dimensional list generator. The elements of this numerical sequence are the numeric values from the range methods, as in the previous examples. Variables i and j are incremented by one in loops and multiplied with each other. The function print serves to visually display the generated data set on the computer screen. Quite often when creating a Python nested list, the null matrix generator is used. As an example, let’s create a 3×2 matrix:

>>> data = [[0 for x in range(2)] for y in range(3)]
>>> print(data)
[[0, 0], [0, 0], [0, 0]]

List generator with lambda

As you know, lambda functions in Python are some kind of operation that returns a value. The advantage of this mechanism is that it can be applied within an expression. This allows you to significantly reduce the amount of code typed by the programmer, because in this case there is no need to declare a new method separately. The list generator with lambda in Python allows Python sometimes uses lambda functions in the list generator. The following example will create a new sequence of numbers resulting from the range method. As before, the element of this set is represented as a variable i, which receives new values (from 0 to 9) step by step in the for loop. The lambda function takes a value as an argument, then multiplies it by itself and returns it back to the generator.

>>> data = [(lambda i: i*i)(i) for i in range(0, 10)]
>>> print(data)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

This creates a list of data that contains the results of the polarization for numbers between 0 and 9. As usual, the print function prints the information on the screen.

Using itertools

To do advanced list generation, Python uses a plugin library called itertools. With it you can create sets of values according to certain rules. To make this module active you need to put the following instruction at the beginning of your script file.

import itertools

The methods in this library let you generate lists that use sophisticated loops. For example, it can easily generate combinations of different values, both symbolic and numeric. The following code is a simple example of generating a list by calling the repeat function.

>>> data = [i for i in itertools.repeat(1, 5)]

>>> print(data)
[1, 1, 1, 1, 1]
As you can see from the result, the method returns a sequence of identical objects (in this case it is number 1) repeated 5 times.

Conclusion

The advanced functionality provided by the list generators in Python allows the programmer to increase the speed and efficiency of data processing. The mechanism considered includes the creation of both regular and multidimensional lists based on certain conditions, as well as using loops. The language also has the ability to generate with lambda-expressions and using the library intertools.

Related Posts

LEAVE A COMMENT