Best way to extend multiple lists

Hello,

This is a problem i have often. When building up a visualization, I get data from different models. Usually I implement a function on the model that returns a list with the features. All features need to be combined in a single list to include in the ViktorResult object. When only 1 list of features is returned, this is easily done using the += operator. But of multiple lists are used, this does noy work anymore. Let me illustrate with a example.
I would like to do the following:

    @MapView("Kaart", duration_guess=2)
    def visualise_on_map(self, params, entity_id, **kwargs) -> MapResult:
        reference_lines, center_line = get_reference_and_center_lines(params, entity_id)

        features, legend = [], []
        features, legend += reference_lines.get_map_features()
        features, legend += center_line.get_map_features()

        return MapResult(features=features, legend=MapLegend(legend))

But unfortunately this is not allowed so i am stuck with this:

    @MapView("Kaart", duration_guess=2)
    def visualise_on_map(self, params, entity_id, **kwargs) -> MapResult:
        reference_lines, center_line = get_reference_and_center_lines(params, entity_id)

        features, legend = [], []
        features_ref, legend_ref = reference_lines.get_map_features()
        features += features_ref
        legend += legend_ref

        features_center, legend_center = center_line.get_map_features()
        features += features_center
        legend += legend_center

        return MapResult(features=features, legend=MapLegend(legend))

I have a feeling that there must be a better way to do this in python similar to the first example. Anyone has a idea?

Definately not the person with the most authority on what is pythonic or not, so consider these just my 2 cents:

    @MapView("Kaart", duration_guess=2)
    def visualise_on_map(self, params, entity_id, **kwargs) -> MapResult:
        reference_lines, center_line = get_reference_and_center_lines(params, entity_id)

        features_ref, legend_ref = reference_lines.get_map_features()
        features_center, legend_center = center_line.get_map_features()

        return MapResult(features=[*features_ref, *features_center], legend=MapLegend([*legend_ref, *legend_center]))

What i personally like about this is that i find it more explicit to read. I don’t do features=features when calling a function and i never have to make features = <adding other list contents one by one>

3 Likes