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