Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to mimic Golang make() function in Python?

I am trying to rewrite go code to python and I don’t understand how the make() function in Golang works.

As an example I have this code which I’m trying to rewrite to Python:

a = make([]string, 1)
b = make([]int, 1)
c = make(map[string]string)

Any help is appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No need to make anything in Python… or in other words, no need to write a function that mimics make. Unlike Go where you have to be explicit about allocating something, in Python this is implicit as objects are allocated automatically on creation for you.

  • a = make([]string, 1): this is a slice of string of size 1 and capacity 1, in Python you can just create an empty list instead: a = [] and then .append() strings into it. Unlike Go for slices or arrays, Python does not require all elements of a list to be of the same type. If you want you could create a = [None] just to be able to index the list right away (in general a = [default_value] * size).
  • b = make([]int, 1): same here, just b = [] or b = [0] if you need to index the list right away. Note that Go initializes all elements to 0 for []int.
  • c = make(map[string]string): this creates a map with string as keys and values. Closest thing in Python would be a dictionary: c = {}. And again, you are not constrained by types in Python so you can later do c["foo"] = "bar" without a problem.

NOTE THAT Go slices have different semantics than Python slices. Doing a[1:10] in Go creates a slice that is merely a view on the underlying object, while in Python a[1:10] copies all the elements creating a new list.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading