Skip to content
Advertisement

Python equivalent for C#’s generic List

I am creating a simple GUI program to manage priorities.

Priorities

I have successfully managed to add functionality to add an item to the listbox. Now I want to add the item to the something what is known as List<> in C#. Does such a thing exist in Python?

For instance, in C#, to add an item to the listview I would first create:

JavaScript

…and then create the following method:

JavaScript

Advertisement

Answer

Type hints

Since Python 3.5, it’s possible to add type hints. Coupled with dataclasses (Python 3.7+), and generic collections (Python 3.9+), you can write:

JavaScript

In Python 3.5, the code would look like:

JavaScript

Note that type hints are optional, and the above code will run fine, even if there’s a type mismatch when appending baz.

You can explicitly check for errors with mypy:

JavaScript

Dynamic language

Even if it now has type hints, Python stays dynamic, and type hints are completely optional:

JavaScript

You don’t have to define anything before appending any object to an existing list.

Python uses duck-typing. If you iterate on a list and call a method on each one of the elements, you need to make sure that the elements understand the method.

So if you want the equivalent of :

JavaScript

you just need to initialize a list and make sure you only add Priority instances to it. That’s it!

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement