Methods for lists and sets
Now that we hopefully really understand OOP, let us take a look at some methods provided by different built-in Python collections.
List methods
lst.sort()- sorts the list in-place (does not return it – it returnsNone). This is called a mutator method. Use the functionsorted()if you want a copy returned instead.lst.reverse()- reverses the list in-place (again does not return it). Use the functionreversed()if you want a copy returned.lst.insert(index, value)- insertsvalueat the givenindexshifting elements to the rightlst.append(value)- adds the value to the end of the list (does not return it)lst.index(value)- returns the index of the first instance ofvaluelst.remove(value)- removes the first instance ofvaluelst.extend(lst2)- adds the elements oflst2to the end oflstlst.count(value)- counts the number of instances ofvaluein the listlst.pop(index)- removes and returns the element at the given index (removes and returns the last item ifindexis not givenlst.clear()- empties the list
Set methods
- These are equivalent to the set operators discussed in earlier modules
s1.union(s2)s1.intersection(s2)s1.difference(s2)s1.symmetric_difference(s2)s1.issubset(s2)s1.issuperset(s2)
s1.isdisjoint(s2)- returns if there are no common elementss.add()- adds a single element to the sets.update()- adds multiple elements to the sets.intersection_update()- modifies a set by intersections.difference_update()- modifies a set by differences1.symmetric_dfference_update(s2)- modifies a set by symmetric differences.discard(elem)- removeselemifelemis in the sets.remove(elem)- removeselemifelemis in the set, otherwise it raises an errors.pop()- removes and returns an arbitrary elements.clear()- removes all elements from the sets