Filter a list of variable length using python list comprehension

  • Consider the below list which contains multiple lists within it.
    Each list within are of variable length.
    To filter these types of lists also, we can use List Comprehension.

    [
    	[1, 5, 'text1', '2020/10/15', ],
    	[2, 10, 'text2'],
    	[3, 20],
    	[4, 30, 'text4', '2021/04/10'],
    	[5, 50]
    ]
    

    See below, samples for different scenarios.

  • Filter columns with data in all positions

    First and second column in the above list have data in all items.
    We can directly apply filter on these columns as in sample below.

    Copied
    from datetime import datetime
    
    list = [
                [1, 5, 'text1', '2020/10/15', ],
                [2, 10, 'text2'],
                [3, 20],
                [4, 30, 'text4', '2021/04/10'],
                [5, 50]
            ]
    
    filteredlist = [ num for num in list if num[0] > 2 ]
    print(filteredlist)
    
    Output:
    [
    	[3, 20],
    	[4, 30, 'text4', '2021/04/10'],
    	[5, 50]
    ]
    
  • List item if a column has data

    Third column is present in come items only.
    In this sample, we are going to list the items that matches a particular text.

    Copied
    list = [
                [1, 5, 'text1', '2020/10/15', ],
                [2, 10, 'text2'],
                [3, 20],
                [4, 30, 'text4', '2021/04/10'],
                [5, 50]
            ]
    
    filteredlist = [ num for num in list if (len(num) > 2 and num[2] == 'text1') ]
    print(filteredlist)
    
    Output:
    [
    	[1, 5, 'text1', '2020/10/15']
    ]
    
  • List item if a column has data or column not present

    In this sample, we will list the items that matches a particular text or if column is not present.

    Copied
    list = [
                [1, 5, 'text1', '2020/10/15', ],
                [2, 10, 'text2'],
                [3, 20],
                [4, 30, 'text4', '2021/04/10'],
                [5, 50]
            ]
    
    filteredlist = [ num for num in list if (
                                                (len(num) > 2 and num[2] == 'text1')
                                                or
                                                (len(num) == 2)
                                            ) ]
    print(filteredlist)
    
    Output:
    [
    	[1, 5, 'text1', '2020/10/15'],
    	[3, 20],
    	[5, 50]
    ]
    
Absolute Code Works - Python Topics