string = "Python, program!" result = [] for x in string: if x not in result and x.isalnum(): result.append(x) print(result)
This program makes it so if a repeat letter is used twice in a string, it’ll appear only once in the list. In this case, the string “Hello, world!” will appear as
[‘H’, ‘e’, ‘l’, ‘o’, ‘w’, ‘r’, ‘d’]
My question is, how would I go about using a while loop instead of a for loop to achieve the same result? I know there’s really no need to change a perfectly good for loop into a while loop but I would still like to know.
Advertisement
Answer
Here is one way you could do it in a while loop:
text = "Python, program!" text = text[::-1] # Reverse string result = [] while text: if text[-1] not in result: result.append(text[-1]) text = text[:-1] print(result)