-3

I'm fetching data from an API and converting the JSON using requests, then extracting one value from each dict in a list within a dict:

response = requests.get("http://api.open-notify.org/astros.json")
astros = response.json()
print(astros["number"])
[print(astronaut['name']) for astronaut in astros['people']]

The output gives the list of names, as desired, but follows this with a list of 6 None values; I can't see why.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
AltShift
  • 336
  • 3
  • 18

1 Answers1

5

Those are the return values of all the print function calls made in the list comprehension.

>>> x = print('hello')
hello
>>> print(x)
None

Instead of a list comprehension, just use a regular loop:

for astronaut in astros['people']:
    print(astronaut['name'])

list comprehensions are only used when you want to keep the actual list created.

wim
  • 338,267
  • 99
  • 616
  • 750
  • 4
    "list comprehensions are only used when you want to keep the actual list created." Addendum: "and should never be used for side-effects" (e.g. `print`ing). A list comprehension is a cue to the code reader that it's a simple transform of the input iterable to an output list, with no magic-at-a-distance; violate that, and you're writing needlessly confusing code. – ShadowRanger Aug 16 '18 at 00:35
  • So, in trying to be more Pythonesque, I was actually being less so. Thanks, all! – AltShift Aug 17 '18 at 00:35