0

I have a 2d array in the following format:

[[a,b,c], [a], [c,d], [e]]

My objective is to identify all sublists of length 1 and compare the element in that sublist to elements of other sublists. If the element exists, remove both elements from the list.

In this case we look for 'a' in the 2d array and eliminate 'a,b,c' and 'a' from the 2d array.

The result should be:

[[c,d], [e]]

My code is as follows:

templist = list1 #list1 is the list containing all elements
for i in templist:
    if (len(i) == 1):
        if(any(i[0] in templist)):
            templist.remove(i)
            templist.remove([sublist for sublist in mylist if i[0] in sublist])
return templist

On running this code, I get the error - 'bool' object is not iterable. What I am doing wrong and how I can fix my error?

8
  • You shouldn't modify the list while iterating over it. Commented May 3, 2017 at 14:49
  • The error message will tell you (and us) the line the error is on Commented May 3, 2017 at 14:50
  • any(i[0] in templist) doesn't make sense. i[0] in templist returns a boolean, and then you pass it to any which expects an iterable. Commented May 3, 2017 at 14:51
  • "My objective is to identify all sublists of length 1"-- but [e] is also a sublist of length 1? Commented May 3, 2017 at 14:52
  • Yes I am looking for both [a] and [e]. Commented May 3, 2017 at 14:56

1 Answer 1

1

Here is a way how you can achieve this:

Python 3 solution:

ar = [["a","b","c"], ["a"], ["c","d"], ["e"]]
for pos,inner_ar in enumerate(ar):
    if len(inner_ar)==1:
        for i,inner_ar2 in enumerate(ar):
            if i!=pos and any(c for c in inner_ar2 for c in inner_ar):
                del ar[pos]
                del ar[i]
print(ar)

Output:

[['c', 'd'], ['e']]

N.B.: Improvement can be done.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. I will look into where I can make possible improvements to the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.