MathYobani
MathYobani

Reputation: 31

Delete list of lists with a condition in python 2

I am working with "for" in python and I need to delete some lists of T if some conditions are met.

T=[[0, 2, 4, 6], [0, 2, 4, 8], [0, 2, 5, 8], [0, 2, 5, 11], [0, 2, 6, 11], [0, 3, 5, 8], [0, 3, 5, 11], [0, 3, 6, 10], [0, 3, 6, 11], [0, 3, 8, 10], [0, 4, 6, 10], [0, 4, 8, 10], [1, 3, 5, 7], [1, 3, 5, 11], [1, 3, 6, 10], [1, 3, 6, 11], [1, 3, 7, 10], [1, 4, 6, 9], [1, 4, 6, 10], [1, 4, 7, 9], [1, 4, 7, 10], [1, 5, 7, 9], [1, 5, 9, 11], [1, 6, 9, 11], [2, 4, 6, 9], [2, 4, 7, 8], [2, 4, 7, 9], [2, 5, 7, 8], [2, 5, 7, 9], [2, 5, 9, 11], [2, 6, 9, 11], [3, 5, 7, 8], [3, 7, 8, 10], [4, 7, 8, 10]]

Example: delete all the lists where the number 1 appears, then

T=[[0, 2, 4, 6], [0, 2, 4, 8], [0, 2, 5, 8], [0, 2, 5, 11], [0, 2, 6, 11], [0, 3, 5, 8], [0, 3, 5, 11], [0, 3, 6, 10], [0, 3, 6, 11], [0, 3, 8, 10], [0, 4, 6, 10], [0, 4, 8, 10], delete([1, 3, 5, 7]), delete([1, 3, 5, 11]), delete([1, 3, 6, 10]), delete([1, 3, 6, 11]), delete([1, 3, 7, 10]), delete[1, 4, 6, 9], delete[1, 4, 6, 10], delete[1, 4, 7, 9], delete[1, 4, 7, 10], delete[1, 5, 7, 9], delete[1, 5, 9, 11], delete[1, 6, 9, 11], [2, 4, 6, 9], [2, 4, 7, 8], [2, 4, 7, 9], [2, 5, 7, 8], [2, 5, 7, 9], [2, 5, 9, 11], [2, 6, 9, 11], [3, 5, 7, 8], [3, 7, 8, 10], [4, 7, 8, 10]]

Is there an algorithm or command in python to do it??

Upvotes: 2

Views: 142

Answers (1)

Mason Caiby
Mason Caiby

Reputation: 1924

You can do this with list comprehesnion: [lst for lst in T if 1 not in lst]

or a for loop:

final = []
for lst in T:
    if 1 not in lst:
        final.append(lst)

If you're working to learn Python, a list comprehension is a single-line for loop for building lists.

List comprehensions are also generally faster than for loops:

def for_loop(T):
    final = []    
    for lst in T:    
        if 1 not in lst:
            final.append(lst)
    return final

def list_comp(T):
    return [lst for lst in T if 1 not in lst]

%timeit for_loop(T)
3.02 µs ± 61.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit list_comp(T)
2.16 µs ± 9.37 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Upvotes: 4

Related Questions