Search code examples
pythonlist-comprehensionnonetype

Bypassing NoneType in a list comprehension


To work around when there is no value x.competition.name, I tried to use is not None:

'competition': [x.competition.name if x.competition.name is not None else '-' for x in a]

But the error still keeps showing up:

AttributeError: 'NoneType' object has no attribute 'name'

How can I go about getting around this problem?


Solution

  • It sounds like you need to test x.competition:

    'competition': [x.competition.name if x.competition is not None else '-' for x in a]