python: the difference between append and extend

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python: the difference between append and extend相关的知识,希望对你有一定的参考价值。

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

An error about list operation in python: append and extend elements

We define a list A to storage objects, which the length is 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 110 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 has nothing in each list

 

Then I research 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, then append the D to the C, 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 will copy all elements in A to the list B, but when using append, it will only copy the address of A to list C, so, in the end, the A will be empty, which caused the result: list C has nothing.

以上是关于python: the difference between append and extend的主要内容,如果未能解决你的问题,请参考以下文章

python: the difference between append and extend

What are the differences between Perl, Python, AWK and sed

What are the differences between Perl, Python, AWK and sed

pay for ; the difference ; their improve without write stop parents instead of a way seldom respect

[lintcode the-smallest-difference]最小差(python)

leetcode?pythonFind the Difference