[Tutor] A simple list question...
Kent Johnson
kent37 at tds.net
Fri Sep 8 05:07:30 CEST 2006
Richard Querin wrote:
> I've got a list of strings. There are some duplicates. I want a list
> of only the unique entries in that list. So I do the following:
>
> mylist = ['project1' , 'project2', 'project3', 'project4', 'project1']
>
> d = {}
>
> for item in mylist:
> d[item] = None
>
> cleanedlist = d.keys()
>
>
> But d.keys() seems to add '\n' to each entry in cleanedlist.
No, it doesn't. You are confused somewhere; my guess is your original
data has newlines. Using your code above exactly:
In [1]: mylist = ['project1' , 'project2', 'project3', 'project4',
'project1']
In [2]: d = {}
In [3]: for item in mylist:
...: d[item] = None
...:
In [4]: cleanedlist = d.keys()
In [5]: cleanedlist
Out[5]: ['project4', 'project1', 'project3', 'project2']
No newlines here.
> 2. Is there a better way to achieve my objective (ie. a list method
> for generating the cleaned list?)
If you don't care about the order of items in the new list, just convert
to a set and back (essentially a more concise version of what you did
with a dict):
In [6]: list(set(mylist))
Out[6]: ['project4', 'project1', 'project3', 'project2']
Kent
More information about the Tutor
mailing list