[Tutor] how to unique the string

Steven D'Aprano steve at pearwood.info
Sat Oct 22 18:50:44 CEST 2011


lina wrote:
> Hi,
> 
> I googled for a while, but failed to find the perfect answer,
> 
> for a string
> 
> ['85CUR', '85CUR']


That's not a string, it is a list.


> how can I unique it as:
> 
> ['85CUR']

Your question is unclear. If you have this:

['85CUR', '99bcd', '85CUR', '85CUR']

what do you expect to get?


# keep only the very first item
['85CUR']
# keep the first copy of each string, in order
['85CUR', '99bcd']
# keep the last copy of each string, in order
['99bcd', '85CUR']
# ignore duplicates only when next to each other
['85CUR', '99bcd', '85CUR']


Does the order of the result matter?

If order matters, and you want to keep the first copy of each string:

unique = []
for item in items:
     if item not in unique:
         unique.append(item)


If order doesn't matter, then use this:

unique = list(set(items))



-- 
Steven



More information about the Tutor mailing list