We help IT Professionals succeed at work.

Filtering Edges of a Graph

TheSilverBullet used Ask the Experts™
I have a graph:

graph = [[1,3],[3,2],[2,1],[7,3],[4,2],[5,4],[6,5],[4,6]]

I would like to write a code (not loop) that could get entries from above graph that start with a certain number.
exmaple graph.get(4)
should give me a list of [[4,2],[4,6]]
I think it could be done with list filter or lambda, but I do not have yet experience in Python.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
The most natural Python way is to use the list comprehension
graph = [[1,3],[3,2],[2,1],[7,3],[4,2],[5,4],[6,5],[4,6]]

result = [item for item in graph if item[0] == 4]
print result

Open in new window

It looks like a for loop, but what is inside the [ ] is actually the expression, and it can be used as such. It prints on my console:
c:\tmp\_Python\TheSilverBullet\Q_27677297>python a.py
[[4, 2], [4, 6]]

Open in new window

Thanks for the points.

If you are used to lambda function and the suite (map, filter, reduce,...), you can also use them.


It was discussed heavily, whether lambda function should be the part of the Python language or not.  It remained in Python probably because many users wanted them.  The truth is that the lambda is not needed that much in Python because of the alternative constructs.