0
x = "haaiiillll"
y=list(x)
z=[]
a=len(y)
n=0
for i in y:
    print(y[n:])
    if i != y[n:]:
        z.append(i)
        n+=1
print(z)

How do I implement this, I can't understand. I have tried to implement a program where it checks if the value with i is there anywhere in the list y if not it will add it otherwise it shouldn't.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Aviral
  • 27
  • 3

4 Answers4

1

This is the simplest way of doing it and works well for lists which aren't very huge:

x = "haaiiillll"
res = [item for i, item in enumerate(x) if x.find(item, i + 1) == -1]
print(res)

output :

['h', 'a', 'i', 'l']

Using .find() we can see if there is any other values equal to item from it's position until the end. (second parameter in find is the starting point)

S.B
  • 13,077
  • 10
  • 22
  • 49
1

As far as I understood, you need to add the element nf the final list only if it appears once in the input list. So, Change the value of n to 1. Keep a set to track whether the element is already seen. And change the condition to check whether the element is in the rest of the list and not seen already.

    n=1
    seen = set()
    for i in y:
        if i not in y[n:] and i not in seen:
            z.append(i)
        seen.add(i)
        n+=1

You problem will be solved.

devReddit
  • 2,696
  • 1
  • 5
  • 20
0
if not your_element in your_list:
    your_list.append(your_element)

This way, an element will be added to the list only if it isn't in the list.

PRO
  • 169
  • 5
  • It's not working. why should it be your_list because that's the list I am already going through – Aviral Jul 18 '21 at 13:54
0

In the list z there will be only elements different from each other:

x = "haaiiillll"
y=list(x)
z=[]
a=len(y)
n=0
for i in y:
    if i not in z:
        z.append(i)
print(z)
SAL
  • 547
  • 2
  • 8
  • 25