"Grammatical sugars", literally, should be a grammar. "Sugar", can be understood as simple, concise. In fact, we have realized that without these grammars, which are called "grammatical sugars", we can also achieve the corresponding functions, while "syntactic sugar" allows us to implement these functions more concisely and quickly. It's just that the Python interpreter translates the syntax of these specific formats into the same complex code logic, nothing too advanced.

In fact, the list generation is also a python "syntax sugar", that is, the list generation should be a python to provide a concise form of the build list, the application of list generation can quickly generate a new list. Its main application scenario is to derive a new list based on an existing iterative object.

3. Usage examples

The requirements for several build lists can be achieved by using "Do not use list generation" and "Use List generation" respectively, and then make a comparison summary.

I think you should have already found that the function of the list generated here is similar to the function of the map () and filter () higher-order functions described in the previous article, such as the following two examples:

Example 1: Converting all strings in a list to lowercase, non-string elements are preserved as-is

For most requirements, the use of list generation and the use of higher-order functions can be achieved. However, some high-order functions, such as map () and filter (), return value types in Python3 into ITERAOTR (iterator) objects (the return value type in the Python2 is list), which is obviously more appropriate for an iterative object with a large or infinite number of elements. Because you can avoid unnecessary waste of memory space. The concept of iterators is described separately below.

Third, generator (Generator)

In terms of name, the generator should be used to generate data.

1. The role of the generator

The new data is continuously generated according to an algorithm until the end of a specified condition is satisfied.

2. How the generator is constructed

There are two ways to construct a generator:

Generated using a similar list-generated form (2*n + 1 for N in range (3, 11))

Use a function that contains yield to generate

If the calculation process is relatively simple, you can directly change the list generation to generator, but if the computational process is more complex, you can only construct generator through a function that contains yield.

Description: In previous versions of Python 3.3, the iteration function method was not allowed to include the return statement.

As you can see, when you use the next () method to traverse the generator, the last is to throw an StopIeration exception to terminate.

Example 2: Using Loop traversal builder

for x in g1: print(x)for x in g2: print(x)

The output of the two loops is the same:

7911

As you can see, using loops to traverse the generator is relatively concise and does not throw an exception at the end StopIeration . Therefore, it is recommended to traverse the generator in a circular fashion.

It is necessary to note that if the generator function has a return value, to get the return value, you can only pass through the next () in a while loop, and finally by catching the StopIteration exception

Send () will call yield, and it will pass a value (the value will be the result of the current yield expression)

It is important to note that the first call to the generator's send () method, the parameter can only be none, otherwise an exception will be thrown. It is also possible to call the next () method before calling the Send () method, in order for the generator to enter the yield expression first.

6. Generator vs. List generation

Now that you can create a new list directly from a list build, why do you have a generator?

Because the list generation is to create a new list directly, it will store all of the data in memory at once, and there are a few problems with the following:

Limited memory capacity, so the list capacity is limited;

When the amount of data in the list is very large, it takes up a lot of memory space, if we just need to access the previous finite elements, it will cause a great waste of memory resources;

When the amount of data is large, the return time of the list generation will be very slow;

The elements in the generator are calculated according to the specified algorithm, and the corresponding data is generated only when the call is made. This eliminates the need to generate all the data at once, thus saving a lot of memory space, which makes the number of elements generated is almost unlimited, and the return time of the operation is very fast (just create a variable).

We can do an experiment: compare the 10 million-digit list to see when the results are returned and the amount of memory space used in the list generation and generator:

As a result, the generator returns almost 0 of the time, resulting in a much smaller amount of memory space than the list generator.

Four, an iterative object (iterable)

We often see "iterable" in Python's documentation, which means "iterative objects". So what is an iterative object?An object that can be used directly for a for loop is called an iterative object (iterable).

The data types that we already know are available as iterations (available for loop) are:

Collection data types: such as list, tuple, dict, set, str, etc.

Generator (Generator)

You can use Isinstance () to determine whether an object is a Iterable object:

import Iterableprint(isinstance([], Iterable))

V. Iterators (Iterator) 1. Definition of iterators

an object that can be called by the next () function and continually returns the next value is called an iterator: Iterator.

It is obvious that the generator mentioned above is also an iterator. Of course, we can use Isinstance () to verify:

from collections import Iteratorprint(isinstance((x for x in range(5)), Iterator))

The output is:True

2. Understanding of Iterators

In fact, the iterator object in Python represents a data stream, and iterator can be continuously returned to the next data by the next () function call until no data can be returned with an StopIteration exception. This data stream can be viewed as an ordered sequence, but we cannot know the length of the sequence in advance. At the same time, the calculation of the iterator is inert, and the next data is calculated and returned only when the next () function is passed. (This section is from here)

The generator is also the case, because the generator is also an iterator.

Vi. the relationship between iterable, iterator and generator

The Builder object is both an iterative object and an iterator: we already know that the generator can function not only with a for loop, but also by the next () function, which is constantly called and returns the next value until the last throw stopiteration error means that the next value cannot continue to be returned. In other words, the generator satisfies the definition of an iterative object and an iterator;

The iterator object must be an iterative object, and vice versa: For example, the collection data types such as list, dict, and Str are iterative objects, but not iterators, but they can generate an iterator object from the ITER () function.

That is, iterators, generators, and iterative objects can all be iterated with a for loop, and generators and iterators can also be called by the next () party function and return the next value.

This article is an English version of an article which is originally in the Chinese language on aliyun.com and is provided for information purposes only. This website makes no representation or warranty of any kind, either expressed or implied, as to the accuracy, completeness ownership or
reliability of the article or any translations thereof. If you have any concerns or complaints relating to the article, please send an email, providing a detailed description of the concern or
complaint, to info-contact@alibabacloud.com. A staff member will contact you within 5 working days. Once verified, infringing content will be removed immediately.

Try 40+ Products For Free !

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.