How can I delete a specific element of a list in a combined list of lists?

Viewed 91

I am trying to find a way to check a list which contains several other lists for a specific element and delete it.

So basically I have 2 lists (a and b) which are combined in another list (c)

a= ["aa","bb"]
b= ["aa","dd"]
c=[a,b]

Now I am trying to delete all elements named "aa"

c.remove("aa")

Sadly this doesn't work and I get the error "ValueError: list.remove(x): x not in list" because "aa" is not literally mentioned in c.

In the end I also want to print out all the lists in c and what they contain. Something like that:

c= a: bb, b: dd
  • Is there a way to delete elements in several lists with a single command like I tried with combining them in another list c?

  • And how can I print out the list c in the end similar to how I described it above?

4 Answers

You can use a list comprehension:

a = ['aa', 'bb']
b = ['aa', 'dd']
c = [a, b]

c = [[x for x in sublist if x != 'aa'] for sublist in c]

This solution will remove all 'aa' elements, while list.remove('aa') in a regular for loop will only remove the first occurrence in each sublist.

You'll need to iterate through the individual lists in list c. For example

>>> a = ["aa", "bb"]
>>> b = ["aa", "dd"]
>>> c = [a, b]
>>> for i in c:
...   i.remove("aa")
... 
>>> c
[['bb'], ['dd']]
>>> 

Your desired output looks like a dictionary. You can create this using a dict comprehension, as such:

a= ["aa","bb"]
b= ["aa","dd"]
mylist_names = ['a','b']
c={name:[x for x in vals if x!='aa'] for name, vals in zip(mylist_names, [a,b])}

>>> c
{'a': ['bb'], 'b': ['dd']}

If you don't mind using numpy

import numpy as np

a= ["aa","bb",'cc']
b= ["aa","dd", 'kk']
c= np.asarray([a,b])

to_remove = ['aa']

c = [x[~np.isin(x,to_remove)].tolist() for x in c]

output = [['bb', 'cc'], ['dd', 'kk']]

Should work for everything you need including multiple items you want to get rid of.

import numpy as np

a= ["aa","bb",'cc']
b= ["aa","dd", 'kk']
c= np.asarray([a,b])

to_remove = ['aa', 'kk']

c = [x[~np.isin(x,to_remove)].tolist() for x in c]

output = [['bb', 'cc'], ['dd']]

Related