I'm having a bit of an issue with a while/if statement.
I have a list of values, normally these values will be strings, but sometimes it can return None. Here are two of my attempts:
x = ['One','Two','Three',None,None]
New = []
count=0
for y in x:
while isinstance(y,str):
New.append(y)
count+=1
break
else:
count+=1
New.append('New - '+str(count))
print New,count
>>> The list repeats several times
New = []
for y in x:
count=0
if y is not None:
New.append(y)
count+=1
else:
count+=1
New.append('New - '+str(count))
>>>['One','Two','Three','New - 1','New - 1']
I would like the output to be: ['One','Two','Three', 'New - 4', 'New - 5'], and to keep the ordering of the list if the None value was somewhere in the middle.
I'm not sure where I'm going wrong, neither of them are far off. Sorry if this is quite simple i'm still learning. I've looked around this forum for a similar query, some have helped but i still can;t figure it out.
Another way of resolving this problem is by using the built-in Python function called sorted: here is my example hope it helps
Please give me give me thumbs up if this has help.
You can also try this simple solution
Whenever counting the index and looping over a list, it's best to use
enumerate
. You can also specify a start number if you don't want it to start from0
which is the default. That seems to be the case here, since you appear to want to count starting from1
Also the
while
loop seems pointless. A simpleif
would be sufficient. And if you know the items will beNone
it's probably better to check if it'sNone
rather than checkingisinstance(item, str)
So I believe the solution you're looking for goes something like
This should produce the result that is expected. This could also be written as a list comprehension, if you like.
The output is
You have some semantic errors in your code.
First example in the "while" statement you've put an "else"! "else" follows "if" statement and in this iteration you don't need that.
Second code part. You want to increment the count value every time the for statement is executed but you're setting the value to 0 every time. So after each execution of the for loop it again will be set to 1->0->1->0... So remove the line and put it before starting the for loop.
A while loop + unconditional break is quite odd. It will work the same way with if and no break.
On the line 17
You declaring the count variable inside the loop That means, that on every iteration count variable setting to zero