Which is more Pythonic way?

Question:

I want to write a function to create an empty square matrix have size NxN.
I have 2 ways to write this:

1:

s_matrix = []
create_empty_square_matrix(s_matrix, N)

2:

s_matrix = empty_square_matrix(N)

(Ofcourse, 2 two functions will different a bit. Function create_empty_square_matrix is like a procedure – only manipulate on s_matrix. Function empty_square_matrix create & return a matrix)

Which way is more Pythonic & clearer?

Do you have some suggestions about naming style? I’m not sure about empty_square_matrix & create_empty_square_matrix.

Asked By: Locke

||

Answers:

I’d always prefer the second way.

The problem with the first is that you pass the object that you want to write to as the paramenter (s_matrix), and the caller of the function will have to know that it must be passed an empty list. What happens if the caller passes a dict, or a list that is not empty?

By the way, if you want to do matrix calculations, you should take a look at the NumPy library, it offers many things that standard Python does not.

Answered By: robinst
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.