nemui
nemui

Reputation: 103

How do you delete an item in a lists of lists based on a condition in python?

for example

list = [[1,2,3], [4,5,6,3], [3,7,8,9,10,11,12]]

I would like to delete all occurrences of the number 3. The new list should be:

[[1, 2], [4, 5, 6], [7, 8, 9, 10, 11, 12]]

Upvotes: 0

Views: 118

Answers (3)

Gab
Gab

Reputation: 3520

Python has a feature to go thru a list with a one liner: [each_value for each_value in list]

You can use it with conditions: [each_value for each_value in list if each_value is True]

In your case, you can do it twice to access the sub-lists and exclude the value 3:

my_list = [[1,2,3], [4,5,6,3], [3,7,8,9,10,11,12]]
result = [[item for item in sec_list if item != 3] for sec_list in my_list]

->

[[1, 2], [4, 5, 6], [7, 8, 9, 10, 11, 12]]

Upvotes: 0

gmdev
gmdev

Reputation: 3155

Edit

For ragged, more complicated lists:

def delete_threes(l):
    nl = []
    for s in l:
        if isinstance(s, list):
            nl.append(delete_threes(s))
        elif s != 3:
            nl.append(s)
    return nl

Above is a recursive function that is capable of removing instances of 3 from a list with a ragged shape.

First, we iterate through the list and check if the element is a sublist or another type. If it's a list, we need to recursively delete the 3's from that list, too. This is where the nl.append(delete_threes(s)) comes from. This essentially passes the sublist into the function again, and then appends the resulting list with the 3's removed to the new list, nl.

Original

You can do this with one line using a list comprehension:

l = [[1,2,3], [4,5,6,3], [3,7,8,9,10,11,12]]

filtered_l = [[i for i in sub if i != 3] for sub in l]

Output:

[[1, 2], [4, 5, 6], [7, 8, 9, 10, 11, 12]]

If you don't want a one-liner, you can go for this rather ugly for-loop:

filtered_l = []
for sub in l:
    filtered_sub = []
    for i in sub:
        if i != 3:
            filtered_sub.append(i)
    filtered_l.append(filtered_sub)

Another note: in your question, you define the variable called list. It is discouraged to name your variables/classes/functions the same as built-ins because it can lead to unreadable code and many headaches after tracking down the bugs that doing this causes. Go for something simpler, like nums_list or just l!

Upvotes: 0

Prakash Dahal
Prakash Dahal

Reputation: 4875

This will help you. User remove() function to remove a particular element from list

Note: remove() function wont return anything

list1 = [[1,2,3], [4,5,6,3], [3,7,8,9,10,11,12]]
for l in list1:
  l.remove(3)
print(list1)

Output:

[[1, 2], [4, 5, 6], [7, 8, 9, 10, 11, 12]]

Upvotes: 1

Related Questions