8

I'm converting some java code to python code and I ended up getting stumped on how to convert a 2D array of objects in Java to python.

Java code:

private Node nodes[][] = new Node[rows][columns];

How would I do this in python?

1
  • Basically, a list of lists. But it's very likely that there's no reason to start with initializing the list. See if a list comprehension works in your case, else write it as a loop with nodes.append([]) and nodes.extend or nodes.append in another loop. Commented Jun 25, 2011 at 20:55

2 Answers 2

13

I think that's what you want

nodes = [[Node() for j in range(cols)] for i in range(rows)]

But it is not always a good practice to initialize lists. For matrices it may make sense.

If you're wondering: Documentation about list comprehensions

Demo code:

>>> class Node:
      def __repr__(self):
        return "Node: %s" % id(self)
>>> cols = 3
>>> rows = 4
>>> nodes = [[Node() for j in range(cols)] for i in range(rows)]
>>> from pprint import pprint
>>> pprint(nodes)
[[Node: 41596976, Node: 41597048, Node: 41596904],
 [Node: 41597120, Node: 41597192, Node: 41597336],
 [Node: 41597552, Node: 41597624, Node: 41597696],
 [Node: 41597768, Node: 41597840, Node: 41597912]]
Sign up to request clarification or add additional context in comments.

4 Comments

curious if you forgot a [ ] in there?
It looks funny; I would have assumed it would have been something like: nodes = [[Node() for j in range(cols)], [for i in range(rows)]]
@nobody what you wrote doesn't even work. I used nested list comprehensions
Couldn't/shouldn't you use _ in place of the names j and i, given that you're only including anything there for synthetic reasons and you don't actually want the values stored anywhere?
0

Python doesnt really do 2d arrays. Here is a better explenation

Its does lists instead

Comments

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.