# Adjacency list representation of directed graph in python

Python program for Adjacency list representation of directed graph. Here problem description and explanation.

``````#    Python 3 Program for
#    Directed graph representation using adjacency list
class AjlistNode :
#  Vertices node key
def __init__(self, id) :
#  Set value of node key
self.id = id
self.next = None

class Vertices :
def __init__(self, data) :
self.data = data
self.next = None
self.last = None

class Graph :
#  Number of Vertices
def __init__(self, size) :
#  Set value
self.size = size
self.node = [None] * (size)
self.setData()

#  Set initial node value
def setData(self) :
if (self.size <= 0) :
print("\nEmpty Graph")
else :
index = 0
while (index < self.size) :
#  Set initial node value
self.node[index] = Vertices(index)
index += 1

#  Connect two nodes
def connect(self, start, last) :
edge = AjlistNode(last)
if (self.node[start].next == None) :
self.node[start].next = edge
else :
#  Add edge at the end
self.node[start].last.next = edge

#  Get last edge
self.node[start].last = edge

#   Handling the request of adding new edge
if (start >= 0 and start < self.size and
last >= 0 and last < self.size) :
#  Safe connection
self.connect(start, last)
else :
#  When invalid nodes
print("\nHere Something Wrong")

def printGraph(self) :
if (self.size > 0) :
index = 0
#  Print graph ajlist Node value
while (index < self.size) :
print("\nAdjacency list of vertex ", index , end = " :")
temp = self.node[index].next
while (temp != None) :
#  Display graph node
print(" ", self.node[temp.id].data, end = " ")
#  visit to next edge
temp = temp.next

index += 1

def main() :
#  5 implies the number of nodes in graph
g = Graph(5)
#  Connect node with an edge
#  print graph element
g.printGraph()

if __name__ == "__main__": main()``````

Output

``````Adjacency list of vertex  0 :  1
Adjacency list of vertex  1 :  2   4
Adjacency list of vertex  2 :  0   3
Adjacency list of vertex  3 :
Adjacency list of vertex  4 :  3`````` ## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.