It's not that easy because in python the square brackets define a list, not an array. A list doesn't force you to have the same type of element (in your case Node) throughout the list.
Some options you have:
Iterate through the list
The same thing you did in the question.
attributes = []
for node in nodes:
attributes.append(node.attr)
List comprehension
A more pythonic syntax for the previous.
attributes = [node.attr for node in nodes]
Map a function on this list
This requires you to define a function that receives a node and returns an attribute of that node.
def get_attr(node)
return node.attr
# or alternatively:
get_attr = lambda node: node.attr
attributes = map(getattr, nodes)
Vectorize this function and pass an array as an argument
This is probably the closest to what you want to do. It requires two things: to vectorize the previous function and to convert nodes to an array.
import numpy as np
get_attr_vec = np.vectorize(get_attr)
nodes = np.array(nodes)
attributes = get_attr_vec(nodes)
To reproduce this example you need to define the list of nodes first:
class Node:
def __init__(self, a):
self.attr = a
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
nodes = [n1, n2, n3]
Also you can use the built-in function getattr instead of the dot syntax.
# These two are the same thing:
a = node.attr
a = getattr(node, 'attr')
print([n.attribute for n in nodes])