Search code examples
pythonlist-comprehensionnonetype

AttributeError 'Nonetype' object has no attribute. But i check for Nonetype


I get AttributeError: 'NoneType' object has no attribute 'rstrip'

So I added if clist is not None: But I keep getting the same error. Why?

if clist is not None:
    result = [
        [name, clist.rstrip()] 
        for name, clist in zip(
            fragments[::group_count+1],
            fragments[group_count::group_count+1]
        )
    ]

Full traceback

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [85], in <module>
    120             fragments = fragments[1:]
    121         if clist is not None:
--> 122             result = [
    123                 [name, clist.rstrip()] 
    124                 for name, clist in zip(
    125                     fragments[::group_count+1],
    126                     fragments[group_count::group_count+1]
    127                 )
    128             ]

Input In [85], in <listcomp>(.0)
    120             fragments = fragments[1:]
    121         if clist is not None:
    122             result = [
--> 123                 [name, clist.rstrip()] 
    124                 for name, clist in zip(
    125                     fragments[::group_count+1],
    126                     fragments[group_count::group_count+1]
    127                 )
    128             ]

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

Solution

  • Try This.

    Clist out of the list comprehension is not None But Some of the value inside fragments in None, THis is why you get this error.

    You need to add if clist is not None inside list comprehension like Below.

    result = [[name, clist.rstrip()] for name, clist in zip(
                fragments[::group_count+1],
                fragments[group_count::group_count+1]
            ) if clist is not None]