|remove()|removes an item from the list| |pop()|removes and returns an element at the given index and returns the item| |clear()|removes all items from the list| |index()|returns the index of the first matched item|
Examples
l = [1, 2, 3, 4, 5]l.append(6)print("append: ", l)l.extend([7, 8, 9])print("extend: ", l)l.insert(0, 0)print("insert: ", l)l.remove(4) # removes the first 4, not the index 4print("remove: ", l)
print(l)print("remove: ", l)l.pop(0) # removes the first elementprint("pop: ", l)l.pop() # removes the last elementprint("pop: ", l)mi = l.index(3) # returns the index of 3print("index: ", l)l.clear() # removes all elementsprint("clear: ", l)
people = {"name": "Nathan", "age": 38, "is_happy": True}j = people.pop("name")print("value of j", j)print("value of people:", people)people.pop("age")print("value of people after 2nd pop: ", people)
value of j Nathan
value of people: {'age': 38, 'is_happy': True}
value of people after 2nd pop: {'is_happy': True}
Other Dictionary Methods
Method
Explanation
.clear()
removes all items from the dictionary
.copy()
returns a shallow copy of the dictionary
.fromkeys()
returns a dictionary with the specified keys and values
.get()
returns the value of the specified key
Other Dictionary Methods, cont.
Method
Explanation
.items()
returns a list containing a tuple for each key value pair
.keys()
returns a list containing the dictionary’s keys
.popitem()
removes the last inserted key-value pair
.values()
returns a list of all the values in the dictionary