Question

I have following code from which I expect the output as : ['abcdef'] ['def']. I want the a2 list to contain unique elements of a1 that are not present in variable x.

>>> a1=[]
>>> a2=[]
>>> a1.append("abcdef")
>>> x="abc"
>>> if x not in a1:
...     a2.append(a1)
... 
>>> print a1, a2
['abcdef'] [['abcdef']]

Any help is appreciated.

Was it helpful?

Solution

this should work. you need to compare each letters one by one then append them to a new string

a1=[]
a2=[]
a1.append("abcdef")
x="abc"
y = "abcdef"
new = ""
for letter in y:
    if letter not in x:
        new = new + letter

a2.append(new)

print a1, a2

output:

['abcdef'] ['def']
[Finished in 0.0s]

this version will check each item in the list vs a single string to check if the string is in any of those

a1=[]
a2=[]
a1.append("abcdef")
x="abc"
new = ""
for item in a1:
    for letter in item:
        if letter not in x:
            new = new + letter

a2.append(new)

print a1, a2

OTHER TIPS

If you really only care about unique letters, you can do this very easily using sets:

>>> set('abcdef') - set('def')
{'a', 'b', 'c'}

If you need the answer as a string, then you can do ''.join(set('abcdef') - set('def').

Note that this doesn't keep the elements in any particular order (they happen to be alphabetical here, but the internal order of a set is arbitrary).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top