The pop () function in the [Python] dictionary and List

Source: Internet
Author: User

In dictionaries and lists, the pop () function deletes a specific element and returns the deleted element to the specified variable or discards

First, the dictionary element is deleted

1.1 Clear ()

Syntax: Dict.clear ()

1 x = {'a'b' 'C': 3  }2x.clear ()3print(x,m)4# Output 5 {} None

Description: Delete all the elements

1.2 Pop ()

Syntax: Dict.pop (Key,[value])

Note: Deletes the specified key and the corresponding value, if the key and value are not present in the dictionary, returns the value corresponding to the key specified in pop (), which sets the default value.

1x = {'b': 2,'C': 3}2m = X.pop ('a', 1)3 Print(x)4 Print(m)5 #Output6{'C': 3,'b': 2}71

1.3 Popitem ()

Syntax: Dict.popitem ()

Description: Randomly deletes one of the key-value pairs and returns a two-element tuple consisting of a key-value pair

x = {'a': 1,'b': 2,'C': 3}m=X.popitem ()Print(x)Print(m)#Output{'a': 1,'b': 2}('C', 3)

2 List Element deletion

Syntax: List.pop (Index)

Note: Delete value at index, or delete the last element by default if index is not specified

x = [1,2,3,4,5= x.pop (0)print  (x)print  (m)# Output [2, 3, 4, 5]1= [1,2,3,4,5= x.pop ()print  (x)  Print  (m)# output [1, 2, 3, 4]5

The pop () function in the [Python] dictionary and List

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.