By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,944 Members | 1,819 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,944 IT Pros & Developers. It's quick & easy.

Python 'NoneType' Error

P: 4
I want to print out list pieces without any zeros to make it more readable.
Part of this code is in a while loop.
Expand|Select|Wrap|Line Numbers
  1. import copy
  2. pieces = [ [1,2,3,4,5,6] , [0,0,0,0,0,0], [0,0,0,0,0,0] ]
  3. def formatt (formatt) :
  4.         while 0 in formatt[1] :
  5.                 formatt[1].remove(0)
  6.         while 0 in formatt[2] :
  7.                 formatt[2].remove(0)
  8.         while 0 in formatt[0] :
  9.                 formatt[0].remove(0)
  10.         print formatt
  11.  
  12.         #part in loop \/
  13.         form = copy.deepcopy(pieces)
  14.         formatt(form)
  15.  
But I getting this error message after the loop runs once:

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

Can anyone help?


-Thanks
mahem1
Jun 5 '11 #1

✓ answered by bvdet

This can be accomplished more succinctly with a list comprehension:
Expand|Select|Wrap|Line Numbers
  1. >>> pieces = [ [1,2,3,4,5,6] , [0,0,0,0,0,0], [0,0,0,0,0,0] ]
  2. >>> [[num for num in item if num != 0] for item in pieces]
  3. [[1, 2, 3, 4, 5, 6], [], []]
  4. >>> 

Share this Question
Share on Google+
3 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
This can be accomplished more succinctly with a list comprehension:
Expand|Select|Wrap|Line Numbers
  1. >>> pieces = [ [1,2,3,4,5,6] , [0,0,0,0,0,0], [0,0,0,0,0,0] ]
  2. >>> [[num for num in item if num != 0] for item in pieces]
  3. [[1, 2, 3, 4, 5, 6], [], []]
  4. >>> 
Jun 6 '11 #2

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

-Thanks
mahem1
Jun 6 '11 #3

Expert 100+
P: 621
'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.
Expand|Select|Wrap|Line Numbers
  1. def formatt (formatt) : 
Jun 9 '11 #4

Post your reply

Sign in to post your reply or Sign up for a free account.