# Looping around self defined indices

How can we effectively shorten the following piece of code:

g=graphs.CirculantGraph(8,[1,2])
v=g.vertices()
v1=set(v)-set([0,4])
v2=set(v)-set([1,5])
v3=set(v)-set([2,6])
v4=set(v)-set([3,7])
v5=set(v)-set([0,5])
v6=set(v)-set([1,4])
v7=set(v)-set([2,7])
v8=set(v)-set([3,6])
g1=g.subgraph(v1)
g2=g.subgraph(v2)
g3=g.subgraph(v3)
g4=g.subgraph(v4)
g5=g.subgraph(v5)
g6=g.subgraph(v6)
g7=g.subgraph(v7)
g8=g.subgraph(v8)


Like, I wish to loop on the indices g(i). Instead of writing repeatedly g1=subgraph(v1) and so on, is there a way to loop arounfd the self defined index g(i)? Thanks beforehand.

edit retag close merge delete

Sort by » oldest newest most voted You can use list comprehension:

G = graphs.CirculantGraph(8,[1,2])
v = G.vertices()
u = [[0,4], [1,5], [2,6], [3,7], [0,5], [1,4], [2,7], [3,6]]
g = [G.subgraph(set(v) - set(s)) for s in u]


You can refer to the $i$-th subgraph by g[i]. You can loop around as usual in Python. For example,

for sg in g:
show(sg)


or

for i in range(len(g)):
show(g[i])

more