Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique items in python list

Tags:

python

I am trying to make a unique collection of dates in a Python list.

Only add a date to the collection if it not already present in the collection.

timestamps = []

timestamps = [
    '2011-02-22', '2011-02-05', '2011-02-04', '2010-12-14', '2010-12-13', 
    '2010-12-12', '2010-12-11', '2010-12-07', '2010-12-02', '2010-11-30', 
    '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16']

date = "2010-11-22"
if date not in timestamps:
    timestamps.append(date)

How would I sort the list?

like image 740
Rajeev Avatar asked Dec 04 '22 09:12

Rajeev


1 Answers

You can use sets for this.

date = "2010-11-22"
timestamps = set(['2011-02-22', '2011-02-05', '2011-02-04', '2010-12-14', '2010-12-13', '2010-12-12', '2010-12-11', '2010-12-07', '2010-12-02', '2010-11-30', '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16'])
#then you can just update it like so
timestamps.update(['2010-11-16']) #if its in there it does nothing
timestamps.update(['2010-12-30']) # it does add it
like image 180
Jakob Bowyer Avatar answered Dec 22 '22 18:12

Jakob Bowyer