0

While many examples succeed in using hints to describe the items carried by a list, I'm stumbling in their declarations.

I'm willing to manipulate (receive, return, create internally) lists of integers.
Accordingly, I'm using list[int] to mention them.

But my code fails with the message: TypeError: 'type' object is not subscriptable, at the first (def) line.

def filtre_valeurs_paires(valeurs: list[int]) -> list[int]:
    valeurs_entieres: list[int] = list(filter(lambda valeur: valeur % 2 == 0, valeurs));
    return valeurs_entieres;

candidats: list[int] = [5, 8, -2, 23, 11, 4];
print("Les valeurs paires dans {} sont : {}".format(candidats, filtre_valeurs_paires(candidats)));

The desired output is a list of even integers: [8, -2, 4].

Marc Le Bihan
  • 2,308
  • 2
  • 23
  • 41
  • 1
    Add this to the top of your imports: `from __future__ import annotations` – Edo Akse Mar 06 '23 at 07:21
  • "Accordingly, I'm using `list[int]` to mention them." This is not supported in the version of Python you are using. Please see the linked duplicate for details. – Karl Knechtel Mar 06 '23 at 07:56

1 Answers1

0

The built-in filter() function returns an object of <class 'filter'>. Trying to assign that to a variable of type list[int] is clearly wrong.

You can correct this with:

def filtre_valeurs_paires(valeurs: list[int]) -> list[int]:
    valeurs_entieres: list[int] = list(filter(lambda x: x % 2 == 0, valeurs))
    return valeurs_entieres

candidats: list[int] = [5, 8, -2, 23, 11, 4]
print("Les valeurs paires dans {} sont : {}".format(candidats, filtre_valeurs_paires(candidats)))
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • I've corrected my code on my opened post, and the `from __future__ import annotations` @EdoAkse suggests made it work. – Marc Le Bihan Mar 06 '23 at 07:29
  • @MarcLeBihan Now that you've done that, your question is irrelevant as it doesn't contain any error(s) (apart from the unnecessary use of semi-colons). You can delete it now – DarkKnight Mar 06 '23 at 07:34
  • @Pingu in fact, it does cause a problem as reported by OP. This is because `list[int]` is not a valid annotation in older versions of Python; it must use `typing.List` instead of the `list` builtin. – Karl Knechtel Mar 06 '23 at 07:58
  • @KarlKnechtel Fair comment but shouldn't we be encouraging people to use up-to-date versions of Python? – DarkKnight Mar 06 '23 at 13:50
  • Arguably. Many people will have various reasons why they need to stick on an earlier minor version, which is why the dev team has the overlapping release schedule that it does. Anyway, the linked duplicate explains both the version issue and the workaround in earlier versions. – Karl Knechtel Mar 06 '23 at 19:39