<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def expand_instances(config_ids, ext_maps):
 """ Iterates over a list of input configuration ids, expanding configured instances if ``None`` is specified. Otherwise where instance names are specified as a tuple, they are expanded. :param config_ids: Iterable of container configuration ids or (map, config, instance names) tuples. :type config_ids: collections.Iterable[dockermap.map.input.InputConfigId] | collections.Iterable[tuple[unicode | str, unicode | str, unicode | str]] :param ext_maps: Dictionary of extended ContainerMap instances for looking up container configurations. :type ext_maps: dict[unicode | str, ContainerMap] :return: MapConfigId tuples. :rtype: collections.Iterable[dockermap.map.input.MapConfigId] """

    for type_map_config, items in itertools.groupby(sorted(config_ids, key=get_map_config), get_map_config):
        config_type, map_name, config_name = type_map_config
        instances = _get_nested_instances(items)
        c_map = ext_maps[map_name]
        try:
            c_instances = _get_config_instances(config_type, c_map, config_name)
        except KeyError:
            raise KeyError("Configuration not found.", type_map_config)
        if c_instances and None in instances:
            for i in c_instances:
                yield MapConfigId(config_type, map_name, config_name, i)
        else:
            for i in instances:
                yield MapConfigId(config_type, map_name, config_name, i)