Generators and iterators, shades of Copy

Source: Internet
Author: User
Tags python list

One, iterator

For the Python list's for loop, his internal principle: to see if the next element exists, if it exists, then remove it, and if it does not, stopiteration the exception. (Python internal to exception has been handled)

classListiterator (object)|Methods defined here:| |__getattribute__(...) | X.__getattribute__('name') <==>X.name| |__iter__(...) | X.__iter__() <==>iter (x)| |__length_hint__(...) |Private Method Returning an estimate of Len (list (it)).| |Next (...)| X.next (), the next value,or RaiseStopiterationlistiterator

Second, generator

With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.

So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the Generator (Generator).

There are a number of ways to create a generator. The first method is simple, as long as a list-generated formula is [] changed () , a generator is created, or the generator is created internally based on yield, that is, the generator is created only when it is used, so that memory waste is not avoided

So, after we create a generator, we basically never call next() the method, but iterate through the for loop.

Generator is very powerful. If the calculated algorithm is more complex, and the loop with similar list generation for cannot be implemented, it can also be implemented with functions.

For example, the famous Fibonacci sequence (Fibonacci), except for the first and second numbers, can be summed up by the top two numbers:

1, 1, 2, 3, 5, 8, 13, 21, 34, ...

Three, depth copy

When making changes, you want to keep the original data and the modified data, while the deep copy in Python is different, especially if the number string and the collection are modified:

When modifying data: For numeric strings, re-create a new copy of the data in memory, and the collection is to modify the same data in memory

For the elements in the List,tuple,dict,set, if you want to make a copy of the subsequent changes, it is best to make a deep copy of the comparison is not easy to error, otherwise it is very error-prone.

In Python, there is a difference between the assignment of an object and the copy (deep/shallow copy), which can produce unexpected results if used without notice.

Actually, this is the result of shared memory.

Copy: The principle is to separate the data, copy its data, and later modify the non-impact.

Let's look at a non-copy example.

= Assignment: Data is fully shared (= assignment is pointing to the same object in memory, if it is a variable (mutable) type, such as a list, modify one, and the other must change

If the immutable type (immutable), such as a string, modifies one, the other does not change

Shallow copy: Data semi-share (copy its data independent memory storage, but only copy the first layer of success)

L1 = [1,2,3,[11,22,33]]l2=l1.copy ()Print(L2)#[1,2,3,[11,22,33]]l2[3][2]='AAA'Print(L1)#[1, 2, 3, [One, one, ' aaa ']Print(L2)#[1, 2, 3, [One, one, ' aaa ']l1[0]=0Print(L1)#[0, 2, 3, [One, one, ' aaa ']Print(L2)#[1, 2, 3, [One, one, ' aaa ']Print(ID (L1) ==id (L2))#flase

Compare the memory address of L2 and L1: False, indicating that L2 in memory has been partially copied L1 data, but only a shallow copy, the second layer of data is not a successful copy, but point to the second layer of data in the memory address of the L1, so the shared memory ' equals ' equal value assignment ', So there will be a change in the second layer of data in the L2, and the second layer of data in L1

, this is the principle of shallow copy, L2 copy L1 only the first layer, that is, in other memory to recreate the L1 of the first layer of data, but L2 can not copy the L1 of the second layer of data, that is, the list of the list, so he can only point to the second layer of data in the L1

Thus, when the second layer of data in the L1 is modified, the second layer of data in a shallow copy of the L1 is changed accordingly.

Deep copy: Data is not shared at all (copying its data completely independent of one memory, full copy, data not shared)

A deep copy is a completely duplicated copy, and the data does not interact with each other because the memory is not shared.

The deep copy method has

Import Module

Import= [1, 2, 3, [one, all]]#  L2 = copy.copy (L1)  shallow copy L2 = Copy.deepcop Y (L1)print(L1,'>>>', L2) l2[3][0] = 1111Print (L1,">>>", L2)

This shows that the deep copy is the data completely independent copies of a copy. Will not change from the original data

Generators and iterators, shades of Copy

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.