Open Pin-Jiun opened 2 years ago
This is the same code as above except that here we don't loop over a copy. Removing an item will shift all following items one place to the left, thus in the next iteration one item will be skipped. This can lead to incorrect results.
for item in a:
if even(item):
a.remove(item)
# --> a = [1, 2, 3] !!!
Also, never modify the index while looping over the list!
This is incorrect because changing i inside the loop will NOT affect the value of i in the next iteration. This example also produces unwanted effects and even lead to IndexErrors like here.
for i in range(len(a)):
if even(a[i]):
del a[i]
i -= 1
# --> IndexError: list index out of range
https://www.python-engineer.com/posts/remove-elements-in-list-while-iterating/
A very common task is to iterate over a list and remove some items based on a condition. This article shows the different ways how to accomplish this, and also shows some common pitfalls to avoid.
Let's say we need to modify the list a and have to remove all items that are not even. We have this little helper function to determine whether a number is even or not.
a = [1, 2, 2, 3, 4]
<p hidden>#more</p>
def even(x):
return x % 2 == 0
1a) Normal List comprehension
Use list comprehension to create a new list containing only the elements you don't want to remove, and assign it back to a.
a = [x for x in a if not even(x)]
# --> a = [1, 3]
https://www.python-engineer.com/posts/list-comprehension/
1b) List comprehension by assigning to the slice a[:] The above code created a new variable a. We can also mutate the existing list in-place by assigning to the slice a[:]. This approach is more efficient and could be useful if there are other references to a that need to reflect the changes.
a[:] = [x for x in a if not even(x)]
# --> a = [1, 3]
1c) Use itertools.filterfalse()
The itertools module provides various functions for very efficient looping and also offers a method to filter items:
from itertools import filterfalse
a[:] = filterfalse(even, a)
# --> a = [1, 3]
If you really want to keep the for-loop syntax, then you need to iterate over a copy of the list (A copy is simply created by using a[:]). Now you can remove items from the original list if the condition is true.
for item in a[:]:
if even(item):
a.remove(item)
# --> a = [1, 3]
#%% list copy pass by reference
a = [1,2,3]
a_ref = a
a.append(4)
print("a: ", a)
print("a_ref: ", a)
a, a_ref 是完全相同的
a 和 a_ref 的記憶體位置相同, 對 a 做修改,a_ref 也會被改變, 也就是所謂的淺複製
淺複製僅複製容器中元素的地址
b = a #直接賦值是屬於淺複製!!
深複製完全複製了一份副本,容器與容器中的元素地址都不一樣
方法一
b = a[:]
方法二 需要import copy模組,裡面有deepcopy函式可以用
import copy
a = [1, [2,3]]
a_deepcopy = copy.deepcopy(a)
How To add Elements to a List in Python append() : append the element to the end of the list. insert() : inserts the element before the given index. extend() : extends the list by appending elements from the iterable. List Concatenation: We can use the + operator to concatenate multiple lists and create a new list.
https://www.digitalocean.com/community/tutorials/python-add-to-list
Python List pop()方法 Python 列表 Python 列表
描述 pop() 函數用於移除列表中的一個元素(默認最後一個元素),並且返回該元素的值。
語法 pop()方法語法:
list.pop([index=-1]) 參數 obj -- 可選參數,要移除列表元素的索引值,不能超過列表總長度,默認為 index=-1,刪除最後一個列表值。 返回值 該方法返回從列表中移除的元素對象。
實例 以下實例展示了 pop()函數的使用方法:
實例
list1 = ['Google', 'Runoob', 'Taobao'] list_pop=list1.pop(1) print "刪除的項為 :", list_pop print "列表現在為 : ", list1 以上實例輸出結果如下:
刪除的項為 : Runoob 列表現在為 : ['Google', 'Taobao']