I want to do
x=[1,2,3,1,1,2,]
y=[1,2]
x-y=[3]

but when I write z=[set(x)-set(y)] if gave:
z=[1,1,2,3]

how I can do it?

For example

z = [item for item in x if item not in y]

should work if you do not want sets.
If you want set difference this should work (can not test in my mobile)

z = set(x)- set(y)
commented: this code works +13

I tested it: z = [item for item in x if item not in y]
but it gave me same result like z=[set(x)-set(y)].
while I want those items in x that there arn't in y.

My test succeeds, strange:

x=[1,2,3,1,1,2,]
y=[1,2]
z = [item for item in x if item not in y]
print(z)
print(set(x)-set(y))
""" Output:
[3]
set([3])
"""

@PyTony do you just write your code in the message body from your mobile or do you have an application for writing code on your mobile? Sorry to digress.

when I test that command( z = [item for item in x if item not in y] or
z=[set(x)-set(y)] ) in python shell with example lists, their results is true . but my real list's item isn't integer and is like this: x=[1acs,1esf,2all,...]. I run it in windows cmd shell.

Member Avatar for Enalicho

If you could provide a better example of the input and output, and post the code you've done, you'll get more help. I'm not certain of what you're asking at the moment; you've been given code that does what you want.

It's important to share the part of the code that you're asking for help on and related items. And are you trying to run those interactively or something? They worked fine for me.

I parsing tow text files line to line that in each line there is a four character that beginning with integer like 2BBI,3HHR,... and appended each file data in separate list because I want to omit repetitive items among them.

@PyTony do you just write your code in the message body from your mobile or do you have an application for writing code on your mobile? Sorry to digress.

I typed it in, unfortunately I have not Python in my Nokia E7 to test if it runs.

BTW the set version and the list comprehension are not equivalent, but would give different results if input would differ (list comprehension does not remove doubles which are in x that are not in y).

are they files created by a module/program? Because if they are then why not just pickle them to a .dat file, load them in your module so you have the lists and use the "z = [item for item in x if item not in y]" idea?

Using a for() loop which may be easier to understand:

input_str = "2BBI,3HHR"
unique_list = []
for ltr in input_str:
    if ltr not in unique_list:
        unique_list.append(ltr)
print unique_list  ## 2BI,3HR
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.