user13924378
user13924378

Reputation: 11

When should square brackets be used in Python function return statement?

I am new to Python and do not understand when square brackets need to be included around a return variable. For example, I have often seen the below format used, where [seed] has the square brackets.

def seed(self, seed=None):
    self.np_random, seed = seeding.np_random(seed)
    return [seed]

Upvotes: 0

Views: 1205

Answers (3)

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5786

The given code will return a list. If you are not returning an list and simply how the seed variable is, you would have simply written - return seed. In your example, you seem to be returning a seed wrapped as a list from the function. So you have to use return [seed].

So,

  • return seed - Returns seed from the function as it is

  • return [seed] - Returns seed from the function by wrapping it in a list. So the value seed will become an element of the newly formed list.

Upvotes: 2

Dinesh
Dinesh

Reputation: 1027

If you want to return a single value, you can use return seed

Or if you want multiple values to be returned, you can use return [seed]

Note: Basically, [] refers to a list of items. you can pass multiple items separated by commas in the list like [1, 7, 6, 'seed']. This will help you to return multiple values at once.

Upvotes: 0

Bryan Oakley
Bryan Oakley

Reputation: 386230

You should use square brackets only when you want to return a list.

return seed returns the seed, return [seed] returns a list with seed as the only element.

Upvotes: 1

Related Questions