Python list 操做小記

 

>>> numbers = [1, 2, 3, 4, 5]
>>> numbers
[1, 2, 3, 4, 5]
>>> numbers[1:4]
[2, 3, 4]
>>> numbers[1:4] = []

>>> numbers
[1, 5]
>>>

clear
The clear method clears the contents of a list, in place.
>>> lst = [1, 2, 3]
>>> lst.clear()
>>> lst
[]
It’s similar to the slice assignment lst[:] = [].
copy
The copy method copies a list. Recall that a normal assignment simply binds another name to the same list.
>>> a = [1, 2, 3]
>>> b = a
>>> b[1] = 4
>>> a
[1, 4, 3]
If you want a and b to be separate lists, you have to bind b to a copy of a.
>>> a = [1, 2, 3]
>>> b = a.copy()
>>> b[1] = 4
>>> a
[1, 2, 3]
It’s similar to using a[:] or list(a), both of which will also copy a.
 




















python

>>> a = [1, 4, 5]
>>> a
[1, 4, 5]
>>> b = a.copy()
>>> b
[1, 4, 5]
>>> c = list(a)
>>> c
[1, 4, 5]
>>> d = a
>>> d
[1, 4, 5]
>>> e = a[:]
>>> e
[1, 4, 5]
>>>
相關文章
相關標籤/搜索