Python lists, dictionaries and other things to be aware of

Source: Internet
Author: User
Tags python list

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.