User Tools

Site Tools


get_unique_items_in_a_list

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:

  1. Order does not matter.
    ['thenandnow', 'debate', 'nowplaying', 'PBS', 'job']

  2. Preserve the order and keep the first unique item.

    ['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']

  3. Preserve the order and keep the last unique item.

    ['PBS', 'nowplaying', 'job', 'debate', 'thenandnow']

Notes and assumptions

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