If speed matters, it may be better to use this:
from operator import iadd
reduce(iadd, (getNeighbors(n) for n in getNeighbors(vertex)))
The point of this code is in concatenating whole lists by list.extend
where list comprehension would add one item by one, as if calling list.append
. That saves a bit of overhead, making the former (according to my measurements) about three times faster. (The iadd
operator is normally written as +=
and does the same thing as list.extend
.)
Using list comprehensions (the first solution by Ignacio) is still usually the right way, it is easier to read.
But definitely avoid using sum(..., [])
, because it runs in quadratic time. That is very impractical for many lists (more than a hundred or so).