Reputation: 5107
I have an empty list
called mylist which looks like
[None,None,None,None,None,None,None]
I have a for loop which will add one to each element each time its past over.
I am trying to add 1 to an element using:
mylist[i] = mylist[i]+1
but I get the error:
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
The number of times the list is iterated over changes so ican't just add one to all elements.
The code I'm using is:
for j in range(0,bucketSize):
for i in range (0,minibuckets):
list[i] = list[i]+1
Upvotes: 0
Views: 93
Reputation: 676
Use a simple list comprehension:
my_list = [None,None,None,None,None,None,None]
print(['1' if v is None else v for v in my_list])
Outputs:
['1', '1', '1', '1', '1', '1', '1']
Upvotes: 0
Reputation: 24107
You should initialise your list to be [0, 0, 0, 0, 0, 0, 0]
, because you cannot do None + 1
. It really doesn't make sense to try to add 1 to something that is effectively nothing. None
is a very different concept than 0.
For example:
mylist = [0] * 7
# or
mylist = [0 for i in range(7)]
Alternatively you can check for None
in your inner for-loop:
if mylist[i] is None:
mylist[i] = 1
else:
mylist[i] += 1
Or the same check in one line:
mylist[i] = mylist[i] + 1 is mylist[i] is not None else 1
Upvotes: 6
Reputation: 11083
You can do something like this if you can not change None
to 0
:
mylist[i] = mylist[i]+1 if mylist[i] else 1
Upvotes: 0
Reputation: 31
None
is very different from 0
. In effect it is no value at all.
The simple solution to this is simply check for None
in your loop.
for j in range(0,bucketSize):
for i in range (0,minibuckets):
if list[i] is None:
list[i] = 1
else:
list[i] = list[i]+1
Alternatively initialize your list to 0
or replace None
with 0
before starting.
Upvotes: 3