Let's look at an example:
Test1 = [' A ', ' B ', ' C ', ', ']
for in test1: if': test1.remove (i) #删除空元素 Print (test1)
>>>[' A ', ' B ', ' C ', ']
At this point, we found that we did not achieve the results we want, the reasons are as follows:
To understand the data structure of a Python list, the list belongs to a continuous linear table, which is contiguous in that there is a contiguous memory that stores the addresses of the elements in the list (ignoring the byte of the address and value, just for the convenience of the example):
Of course, you can prove it by a code:
a=[1,2,3] for in A: print(ID (i))
>>>1514106336 #此地址即为左边的连续地址
1514106368
1514106400
Back to the question, when we delete the empty characters in Test1,
The list has three ways to delete elements, Del,remove,pop, where del is a Python method that is not unique to the list, the pop () parameter is the index of the element, and the Remove () parameter is the value that you want to delete
Use Del to see what happens:
a=[1,2,3] for in A: if i==2: del i print(ID (i))
Nameerror:name ' I ' is not defined
a=[1,2,3] for in A: if i==2: del# del is dereference, and everything in Python is referenced Try : Print (ID (i)) except nameerror: Pass
A delete before address 1927704032 output 1927704032 1927704064 1927704096 1927704096
In contrast to the change of address, it is known that del deleted the element memory address reference.
There are two ways to remove empty elements from the list:
#First KindTest2 = ['a',"','b',"','C',"',"'] while "' inchTest2:test2.remove ("')Print(test2)>>>['a','b','C']#The second KindTest2_new = [i forIinchTest2ifI! ="']#to generate a new list
That is, the specified element in the delete list suggests using both methods, and do not use a for loop.
The above record is to write code to tread on the pit, there are not rigorous or wrong place to expect everyone to correct.
Python list Delete element collation