1

This should be trivial. Yet I don't feel 100% sure about my trick.

I have a list of lists (lol ;)) that captures edge relationships between nodes of a graph. Let's say I have a directed graph with 4 nodes labeled 0, 1, 2, 3. The edges are {(0,2),(0,3),(1,0),(1,3),(2,1)} and so the adjacency lol (call it a) is

a = [[2,3],[0,3],[1],[]]

I want to find the incidence lol now, i.e. a list of lists which indicate which nodes are incident on which nodes. For this example, the incidence lol (call it b) would be:

[[1], [2], [0], [0, 1]]

I tried the following code:

b = [[],[],[],[]]
[b[j].append(i) for i,x in enumerate(a) for j in x]

This gives me the right incidence matrix b.

The second step, although works, should ideally be b[j].append(i) for i,x in enumerate(a) for j in x, without the opening [ and closing ]. But Python interpreter cries syntax error without it. Is there a better way of phrasing it?

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
Nik
  • 5,515
  • 14
  • 49
  • 75

1 Answers1

2

Your question is essentially about using list comprehensions for side effects. As, e.g. the answers to this question say, breaking it down into a for loop (or loops) is the way to go:

for i, x in enumerate(a):
    for j in x:
        b[j].append(i)

Also, please note that list comprehensions are used to construct lists in a very natural, easy way, like a mathematician is used to do. That is why, in Python, syntax requires square brackets (in your case).

Community
  • 1
  • 1
kaspersky
  • 3,959
  • 4
  • 33
  • 50
  • I basically want to avoid loops. Please correct me if I am wrong but my belief is that list comprehension and other in-built functions can be much more efficient than using loops. – Nik Jan 24 '13 at 23:57
  • Indeed, often Python come with some internal optimizations related to list comprehension, but you must think also about the readability of your code. On the other hand, Python's key features doesn't include performance, so it all depends of the purpose of your code. – kaspersky Jan 25 '13 at 00:16