Filter a set using python list comprehension

  • Python Sets are a group of items provided within {}. Below sample shows how to use list comprehension to filter from a python set. Here we have implemented filter of a set of numbers, dates and strings.

    Copied
    from datetime import datetime
    
    numset = {5, 10, 20, 30, 40}
    #Filter numbers from set
    filterednumset = {num for num in numset if num > 15}
    print("Filtered set of numbers: " + str(filterednumset))
    
    strset = {'James', 'Rory', 'Kevin'}
    #Filter name Rory and Kevin
    filteredstrset = {st for st in strset if (st == 'Rory' or st == 'Kevin')}
    print("Filtered set of names: " + str(filteredstrset))
    
    dateset = {'2021/1/2', '2021/1/15', '2022/4/1', '2022/5/2'}
    #Convert string dates to datetime objects
    dtset = {datetime.strptime(dt, '%Y/%m/%d') for dt in dateset}
    #Apply filter by month
    filtereddateset = {dt for dt in dtset if dt.month == 1}
    #Convert datetime to str dates, if needed
    dateslist2str = {datetime.strftime(dt1, '%Y/%m/%d')  for dt1 in filtereddateset}
    print("Filtered dates set: " + str(dateslist2str))
    
    Output:
      Filtered set of numbers: {40, 20, 30}
      Names Filtered set of names: {'Kevin', 'Rory'}
      Filtered dates set: {'2021/01/02', '2021/01/15'}

    If you have dates in different string formats, refer below link to know how to convert.
    Filter a list of string dates in different formats

  • Multi-dimensional sets

    A Python Set is an unhashable object.
    Sets are not allowed an unhashable object within it.
    So a set within a set is not a possibility.
    We can have sets within a list, but it is not possible to apply list comprehension on those.

Absolute Code Works - Python Topics