0

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.

3
  • 1
    In the second one, count gets reset to 0 every time the for loop iterates. Put count above the for loop. Commented Oct 24, 2017 at 16:12
  • If I'm understanding this right... you want to replace None with a string 'New - {number}' where {number} is the position of the item, 1-indexed? Commented Oct 24, 2017 at 16:15
  • @sytech, Yes this is correct, I've done some reading on the enumerate function for formatting so i'll be using this Commented Oct 24, 2017 at 18:45

7 Answers 7

2

First code:

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)

Second Code:

x = ['One','Two','Three',None,None]
New = []
count=0
for y in x:
    if y is not None:
        New.append(y)
        count+=1
    else:
        count+=1
        New.append('New - '+str(count))
print (New,count)

In second piece of code initialize count=0 outside the for loop.

In first code you can also replace 'while' with 'if':

.
.
.    
if isinstance(y,str):
    New.append(y)
    count+=1
else:
.
.
.
Sign up to request clarification or add additional context in comments.

Comments

2

You have some semantic errors in your code.

  1. First example in the "while" statement you've put an "else"! "else" follows "if" statement and in this iteration you don't need that.

  2. 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.

     x = ['One','Two','Three',None,None]
    
     New = []
     count=0
     for y in x:
        if y is not None:
            New.append(y)
            count+=1
        else:
            count+=1
            New.append('New - '+str(count))
    

Comments

1

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 from 0 which is the default. That seems to be the case here, since you appear to want to count starting from 1

Also the while loop seems pointless. A simple if would be sufficient. And if you know the items will be None it's probably better to check if it's None rather than checking isinstance(item, str)

So I believe the solution you're looking for goes something like

x = ['One', 'Two', 'Three', None, None]
new = []
for index, item in enumerate(x, start=1):
    if item is None:
        new.append('New - {}'.format(index))
    else:
        new.append(item)

print(new)

This should produce the result that is expected. This could also be written as a list comprehension, if you like.

new = [item if item is not None else 'New - {}'.format(index) for index, item in enumerate(x, start=1)]

The output is

['One', 'Two', 'Three', 'New - 4', 'New - 5']

Comments

1

On the line 17

You declaring the count variable inside the loop That means, that on every iteration count variable setting to zero

Comments

1

You can also try this simple solution

x = ['One','Two','Three',None,None]
for i in range(0,len(x)):
        if x[i]==None:
            x[i]='New -'+ str(i+1)
print x

Comments

0

A while loop + unconditional break is quite odd. It will work the same way with if and no break.

1 Comment

Yeah sorry I'm quite new to this, I'll do some more background reading to get my head around things.
0

Another way of resolving this problem is by using the built-in Python function called sorted: here is my example hope it helps

# Support problem on Stackflow answered by Waheed Rafi { Wazzie }

import sys

listOfNames = ['John','Waheed','Foo','Boo']


# print in unorder list
for element in listOfNames:
    print(element)
print("--------------------------------------")
print("The new sorted list in Alphabetically")
print("--------------------------------------")
sortedlist = sorted(listOfNames) # python has built-in function call sorted
# print List in order ie alphabetically

for sortedElement in sortedlist:
    print(sortedElement)

Please give me give me thumbs up if this has help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.