get_unique_items_in_a_list
This is an old revision of the document!
Table of Contents
Get unique items in a list
Task
Given
mylist = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
get the list of unique items. This can be one of three ways:
- Order does not matter.
['thenandnow', 'debate', 'nowplaying', 'PBS', 'job']
- Preserve the order and keep the first unique one.
['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']
- Preserve the order and keep the last unique one.
['PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
Assume Python >= 3.9 is used
Case 1: unique unordered
uniq_no_order = list(set(mylist)) print(uniq_no_order)
['nowplaying', 'job', 'debate', 'PBS', 'thenandnow']
Case 2: keep first unique
uniq_first = list({key:1 for key in mylist}.keys()) print(uniq_first)
['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']
Case 3: keep last unique
uniq_last = list({key:1 for key in mylist[::-1]}.keys())[::-1] print(uniq_last)
['PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
get_unique_items_in_a_list.1627077267.txt.gz · Last modified: 2021/07/23 21:54 by raju