Python:the difference between append and extend

Source: Internet
Author: User

Data Analysis:indoor localization using received signal strength (RSS)

An error about the list operation in Python:append and extend elements

We define a list A to storage objects, which the length was unknown, and list B and C to storage the final result.

The code like bellow:

# BEGIN

A = []

B = []

C = []

For obj in range (110):

Add ten objects to a, a = [a0,a1,a2....a9]

B.extend (A)

C.append (A)

Del a[:]

# End

The expected result is:

B = [A0, a1, A2,a3 ..., a 1098, a1099]//which has 1100 elements

C = [[A0, A1....a9], [A10, A11...a19] .... [a1090, a1091...a1099]] which has elements

But when I run the code, the bug appear, the real result as follow:

B = [A0, a1, A2,a3 ..., a 1098, a1099]//which has 1100 elements

C = [[], [] .... []]//which have nothing in each list

Then I the difference between append and extend through Google

Append:append object to the end

Extend:extend List by iterable

Finally, I Print the result in each cycle, the list B using extend looked fine, but the list C using append came wrong, it showed like bellow:

C = [[A1]]

C = [[A2],[A2]]

C = [[A3],[a3],[a3]]

.....

C = [[a109],[a109],... [A109]]

Then I make a deep copy from A to D and then append the D to the C and like bellow:

# BEGIN

A = []

B = []

C = []

For obj in range (110):

Add ten objects to a, a = [a0,a1,a2....a9]

B.extend (A)

D = Copy.deepcopy (A)

C.append (D)

Del a[:]

# End

Run the code and the result came right.

So, when using extend, it'll copy all elements in A to the list B, and when using append, it'll only copy the address of a to list C, so, in the end, the A would be empty, which caused the result:list C have nothing.

Python:the difference between append and extend

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.