[Python] Data Structure

List

1
2
3
4
5
6
7
8
9
10
11
12
# list
myList = [1, 2, 3, True, 2]
myList.append(item)
myList.insert(i, item)
myList.pop()
myList.pop(i)
myList.sort()
myList.reverse()
del myList[i] # Delete the item in the ith position
myList.index(item)
myList.count(item)
myList.remove(item) # Remove the first occurance of item

String

1
2
3
4
5
6
# String
string.center(w) # Returns a string centered in a filed of size w ' David '
string.count(item) # Returns the number of occurance of item in the string
string.lower() # Returns a string in all lowercase
string.find(item) # Returns the index of the first occurance of item
stirng.split(char) # Split a string into substring at char

A big difference between list and string is that lists can be modified while strings cannot. This is referred to as mutability. Lists are mutable, strings are immutable.

Set

A set is an unordered collection of zero or more immutable python data object. Lookup/Insert/Delete O(1) time in averate.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
mySet = {2, 3, 5, 'cat'}
myset.add(item)
myset.remove(item)

mySet.union(otherset)
myset.intersection(otherset)
myset.difference(otherset)
myset.issubset(otherset)

myset.clear()
aset | otherset # Returns a new set with all elements from both sets
aset & otherset # Returns a new set with only those elements common to both sets
aset - otherset # Returns a new set with all items from the first set not in second
aset <= otherset # Asks whether all elements of the first set are in the second

Dictionary

Dictionaries are collections of associated pairs of items where each pair consists of a key and a value.

1
2
3
4
5
myDict = {'david': 1410, 'brad': 12}
myDict.values()
myDict.items()
myDict.get('david', 'NO ENTRY')
d = {key: value for (key, value) in iterable}

Priority Queue

Can be implemented with heapq libary.

1
2
3
4
5
from heapq import *
heap = []
heappush(heap, 1) # min heap
heappush(heap, 2)
heappop(heap)