Python 'NoneType' Error

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Mahem Ones
    New Member
    • Jun 2011
    • 4

    Python 'NoneType' Error

    I want to print out list pieces without any zeros to make it more readable.
    Part of this code is in a while loop.
    Code:
    import copy
    pieces = [ [1,2,3,4,5,6] , [0,0,0,0,0,0], [0,0,0,0,0,0] ]
    def formatt (formatt) :
            while 0 in formatt[1] :
                    formatt[1].remove(0)
            while 0 in formatt[2] :
                    formatt[2].remove(0)
            while 0 in formatt[0] :
                    formatt[0].remove(0)
            print formatt
    
            #part in loop \/
            form = copy.deepcopy(pieces)
            formatt(form)
    But I getting this error message after the loop runs once:

    Traceback (most recent call last):
    File "C:\Documen ts and Settings\Jos\De sktop\Towers of Henoy.py", line 68, in <module>
    formatt(form)
    File "C:\Documen ts and Settings\Jos\De sktop\Towers of Henoy.py", line 37, in formatt
    while 0 in formatt[1] :
    TypeError: 'NoneType' object is not subscriptable

    Can anyone help?


    -Thanks
    mahem1
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    This can be accomplished more succinctly with a list comprehension:
    Code:
    >>> pieces = [ [1,2,3,4,5,6] , [0,0,0,0,0,0], [0,0,0,0,0,0] ]
    >>> [[num for num in item if num != 0] for item in pieces]
    [[1, 2, 3, 4, 5, 6], [], []]
    >>>

    Comment

    • Mahem Ones
      New Member
      • Jun 2011
      • 4

      #3
      That works great!!
      The error:
      'TypeError: 'NoneType' object is not subscriptable' /iterable
      Was because I used 'return pieces' instead of 'return (pieces)'

      -Thanks
      mahem1

      Comment

      • dwblas
        Recognized Expert Contributor
        • May 2008
        • 626

        #4
        'TypeError: 'NoneType' object is not subscriptable' /iterable
        Was because I used 'return pieces' instead of 'return (pieces)'
        I suspect that it was because you use the same name for the function and the variable (which one are you referring to in your code). A variable is of type string, int, etc. A function is probably None type.
        Code:
        def formatt (formatt) :

        Comment

        Working...