Home > other >  The three ways of python list delete elements
The three ways of python list delete elements

Time:09-20

Python list way of removing elements there are three main types:
Remove: removing a single element, remove the first qualifying elements, according to the value delete
For example:
> STR=,2,3,4,5,2,6 [1]
> STR. Remove (2)
> STR
[1, 3, 4, 5, 2, 6]

2. Pop: removing a single or multiple elements, according to a delete (delete) in the index
> STR=,1,2,3,4,5,6 [0]
> STR. Pop (1) # pop delete will return when the deleted element
> STR
[0, 2, 3, 4, 5, 6]
> Str2=[' ABC ', 'BCD', 'the dce]
> Str2. Pop (2)
'the dce'
> Str2
[' ABC 'and' BCD]

3. Del: it is according to the index elements (location) to delete the
For example:
> STR=,2,3,4,5,2,6 [1]
> Del STR [1]
> STR
[1, 3, 4, 5, 2, 6]
> Str2=[' ABC ', 'BCD', 'the dce]
> Del str2 [1]
> Str2
[' ABC ', 'the dce]

In addition, the del can also delete the value of the specified scope,
> STR=,1,2,3,4,5,6 [0]
> Del STR [then] # delete from the second element, until the fourth element (but not including the rear element)
> STR
[0, 1, 4, 5, 6]

Del can also delete the entire data object (list, collection, etc.)
> STR=,1,2,3,4,5,6 [0]
> Del STR
> After deleting the STR #, can not find object

Traceback (the most recent call last) :
The File "& lt; Pyshell# 27 & gt;" , line 1, in
STR
NameError: name 'STR' is not defined

Note: del is deleted references (variable) rather than deleted objects (data), object by automatic garbage collection (GC) to delete,

Supplement: disguised method of removing elements
S1=(6)
S2=(2,3,5)
S3=[]
For I in s1:
If I not in s2:
S3. Append (I)
Print 's1-1:' s1
S1=s3
Print 's2:'
s2Print 's3:', s3
Print 's1-2:' s1
  • Related