0

Is there a way to neatly create large (i.e. indexable) empty lists in python?

This is what I am doing at the moment:

firstgen=G.neighbors(node1)
secgen=[]
thirdgen=[[],[],[],[],[],[],[],[],[],[],[]]  #11 brackets because len(secgen)=11

for i in firstgen:
    secgen.append(G.neighbors(i))   

for i in range(len(secgen)):
    for j in secgen[i]:
        thirdgen[i].append(G.neighbors(j))

What I am doing is finding the neighbors of the neighbors of the neighbors of an original node in a network and so my third generation list of neighbors should have the structure [ [[...],[...],[...]] , [[...],[...],[...]] , [[...],[...],[...]] ] but I am new to python and have not been able to find how to make this work without manually putting in the length of thirdgen.

Sorry for the confusing explanation. I am doing this in order to find triads in the network i.e. if any of the third gen nodes are the same as the initial node then I have found a triad.

Thanks!

EDIT: I just realised that I can simply put thirdgen.append([]) in the first loop. Still curious about other methods though.

2
  • This looks like it could get ugly. Unless you need to do it this way for reasons unknown to me, I would suggest making your own data structure for this, one with methods to handle your specific needs. Commented Jul 10, 2011 at 0:55
  • What do you mean by "empty"? Indexing into a container is what you do to retrieve an element. Normal definitions of "empty" don't allow for the possibility that there actually is an element there to retrieve. It looks like you want a nested list of empty lists; but what are you going to do with it? Please explain much, much more carefully what you are talking about with "networks" and "triads". Commented Jul 10, 2011 at 2:24

3 Answers 3

3

You don't need to create the empty lists. You can use list comprehensions to build your nested lists:

firstgen = G.neighbors(node1)
secndgen = [G.neighbors(node) for node in firstgen]
thirdgen = [[G.neighbors(node) for node in group] for group in secndgen]
  • firstgen: [node, ...]
  • secndgen: [[node, ...], ...]
  • thirdgen: [[[node, ...], ...], ...]
Sign up to request clarification or add additional context in comments.

Comments

2

Perhaps:

thirdgen = [list() for x in range(len(secgen))]
thirdgen = [list() for x in range(11)]

Or I might be misunderstanding the actual question.

1 Comment

list() is more idiomatically spelled [].
2

You could use list generator as follows: [[] for x in range(11)].

1 Comment

That is a list comprehension. A generator would be ([] for x in xrange(11))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.