首页 > 代码库 > python: the difference between append and extend

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