Updating python sets using list comprehension

  • Python Sets are a group of items provided within {}. See below how to update python sets. We can do conditional updates as well.

    Copied
    import datetime
    
    numset = {5, 10, 20, 30, 40}
    updatedset = {num+100 for num in numset if num > 15}.union({num for num in numset if num <= 15})
    print(updatedset)
    
    strset = {'James', 'Rory', 'Kevin'}
    updatedset = {st + " Associate" for st in strset if (st == 'Rory' or st == 'Kevin')}.union(
                {st for st in strset if (not(st == 'Rory' or st == 'Kevin'))})
    print(updatedset)
    
    dateset = {'2021/1/2', '2021/1/10', '2022/4/1', '2022/10/2'}
    #Convert string dates to datetime objects
    dtset = {datetime.datetime.strptime(dt, '%Y/%m/%d') for dt in dateset}
    #Add 30 days, if year is 2022
    updatedset = {dt + datetime.timedelta(days=30) for dt in dtset }
    #Convert datetime to strring dates, if needed
    strdates = {datetime.datetime.strftime(dt1, '%Y/%m/%d')  for dt1 in updatedset}
    print(strdates)
    
    Outputs:
    {
    	130, 5, 120, 10, 140
    }
    
    {
    	'Kevin Associate', 'Rory Associate', 'James'
    }
    
    {
    	'2021/02/01', '2021/02/09', '2022/05/01', '2022/11/01'
    }
    

    Note that, if we apply a filter condition to sets, only the items matching the condition will be returned as the new set.
    To display the complete set, we will have to do a union as in above samples.

Absolute Code Works - Python Topics