Skip to content

Instantly share code, notes, and snippets.

@Clivern
Created March 21, 2021 18:37
Show Gist options
  • Save Clivern/b37652406e7376a86f6aa1740416ba48 to your computer and use it in GitHub Desktop.
Save Clivern/b37652406e7376a86f6aa1740416ba48 to your computer and use it in GitHub Desktop.
Python Lists
import bisect
from heapq import *
class Lists():
def __init__(self, elem):
self.elem = elem
def append(self, x):
# same as self.elem[len(self.elem):] = [x]
# self.elem.insert(len(self.elem), x)
return self.elem.append(x)
def extend(self, elem):
return self.elem.extend(elem)
def insert(self, index, value):
return self.elem.insert(index, value)
def remove(self, x):
"""Removes the first item from the list whose value is equal to x.
It raises a ValueError if there is no such item.
"""
return self.elem.remove(x)
def pop(self, index=None):
"""Remove the item at the given position in the list, and return it.
If no index is specified, a.pop() removes and returns the last item in the list
"""
return self.elem.pop() if index is None else self.elem.pop(index)
def clear(self):
"""Remove all items from the list.
Equivalent to del self.elem[:]
"""
return self.elem.clear()
def len(self):
return len(self.elem)
def index(self, value, start=None, end=None):
"""Return zero-based index in the list of the first item whose value is equal to x.
Raises a ValueError if there is no such item.
The optional arguments start and end are interpreted as in the slice notation and
are used to limit the search to a particular subsequence of the list.
"""
if start is not None and end is not None:
return self.elem.index(value, start, end)
return self.elem.index(value)
def count(self, value):
"""Return the number of times x appears in the list."""
return self.elem.count(value)
def reverse(self):
"""Reverse the elements of the list in place."""
return self.elem.reverse()
def copy(self):
"""Return a shallow copy of the list. Equivalent to a[:]"""
return self.elem.copy()
def sort(self, reverse=False):
return self.elem.sort(reverse=reverse)
def insort(self, value):
"""Inserting items into a sorted list"""
return bisect.insort(self.elem, value)
def bisect(self, value):
"""Inserting items into a sorted list and get the index"""
index = bisect.bisect(self.elem, value)
return self.elem.insert(index, value)
def get_list(self):
return self.elem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment