get_unique_items_in_a_list
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. The output can be one of three ways:
- Order does not matter.
['thenandnow', 'debate', 'nowplaying', 'PBS', 'job']
- Preserve the order and keep the first unique item.
['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']
- Preserve the order and keep the last unique item.
['PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
Notes and assumptions
- Starting from Python 3.7, dictionaries in python are ordered by insertion order. Per https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries
Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order
- Assume Python >= 3.7 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.txt · Last modified: 2021/07/23 22:14 by raju