The list in 1.python is not able to traverse delete
1 #Python list We are not able to traverse delete2Li = [1, 2, 3, 4, 5, 6]3 forIinchRange (len (LI)):4 Print(i)5 delLi[i]6 Print(LI)7 #Output Result:8 #Traceback (most recent):9 #0Ten #[2, 3, 4, 5, 6] One #File "C:/users/xzb/pycharmprojects/s1/day7/python considerations. Py", line 5, <module> A #1 - #del Li[i] - #[2, 4, 5, 6] the #indexerror:list Assignment Index out of range - #2 - #[2, 4, 6] - #3
Cause: First, the list is a mutable type of data, each time we make a modification, will be modified above the original data type, however, for traversal has a mechanism, at the first time, it will need to traverse how many secondary related storage, so the subsequent traversal will not be judged how many times, so, When the for traversal of the elements in the list, we did not iterate, the list of elements will change, however, the mechanism of the for traversal is the original, so there will be a mistake to delete!
Dictionaries in 2.python are not able to traverse delete
1DIC = {'K1':'v1','K2':'v2','A3':'v3'}2 forIinchDIC:3 Print(i)4 if 'k' inchI:5 delDic[i]6 #output: Traceback (most recent call last):7 #K18 #File "C:/users/xzb/pycharmprojects/s1/day7/python considerations. Py", line A, in <module>9 #For i in DIC:Ten #runtimeerror:dictionary changed size during iteration
If we print out key-value pairs that do not contain k, there are two ways to do it:
1 #Method One2DIC = {'K1':'v1','K2':'v2','A3':'v3'}3Dic1 = {}4 forIinchDIC:5 if 'k' not inchI:6 Dic1.setdefault (i, dic[i])7DIC =Dic18 Print(DIC)9 Ten #Method Two OneL = [] ADIC = {'K1':'v1','K2':'v2','A3':'v3'} - forIinchDIC: - if 'k' inchI: the l.append (i) - - forIinchL: - delDic[i] + - Print(DIC)
List in Python, dictionaries, and other things you must be aware of