Python Data Structure

Data Structure

Set


HashMap

OrderedDict

hashmap + doubly-linked list


List

  • nums.sort(): Sorts the list in-place. O(nlogn)

    • sorted(nums) : Returns a new list that is sorted.

  • [x + y for x in nums]: iterating through a nested list. O(n)

  • nums.insert(index, x): Inserts x at the specified index in the list. O(n) in the worst case.

  • nums.index(x) :Returns the first index of the element x in the list. O(n)

  • nums.remove(x): Removes the first occurrence of x from the list. O(n) in the worst case.

    • If x is not in the list, it raises a ValueError.

  • nums.pop(index) : Removes and returns the element at the specified index. O(n)

    • nums.pop(): If no index is specified, it removes and returns the last item. O(1)

  • nums.clear() : Removes all elements from the list. O(n)

  • nums[::-1] : Reverse O(n)

  • nums.count(x) : Returns the number of occurrences of x in the list. O(n)

  • zip(list1, list2): Combines two (or more) iterables (like lists) into an iterator of tuples, where the i-th tuple contains the i-th element from each iterable. O(min(n,m))

  • map(func, iterable) : Applies a function func to each item of the iterable and returns an iterator yielding the results. O(n)

  • filter(func, iterable): Filters elements from the iterable where func returns True and returns an iterator of the filtered results. O(n)

Stack


Deque


Heap

Your own Comparison

  1. Use Tuple

  2. Wrap objects and implement __lt__

  3. Use functools.cmp_to_key inside a wrapper object

Last updated