Removing sublists from a list in Python

Question:

I have a list C. I want to remove all sublists which have length 7. But I am getting an error. I present the expected output.

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

for i in range(0,len(C)):
    if(len(C[i])==7):
        C.remove(C[i])

The error is

 in <module>
    if(len(C[i])==7):

IndexError: list index out of range

The expected output is

[[0, 2, 3, 5], [1, 3, 4, 6], [2, 0, 3, 5]]
Asked By: rajunarlikar123

||

Answers:

You are modifying the list you are iterating on, so after you have removed an element, your example list only has length 4, which is why you get this error. To solve this, you need to use an auxiliary list:

result = []
for sublist in C:
    if len(sublist) != 7:
        result.append(sublist)

or you can use the builtin filter:

list(filter(lambda x: len(x)!= 7, C))
Answered By: Florent Monin
C = [[0, 2, 3, 5], [1, 3, 4, 6], [2, 0, 3, 5], [3, 0, 1, 2, 4, 5, 6], [8, 5, 6, 7, 9, 10, 11]]

new_C = [item for item in C if len(item) != 7]
Answered By: BoroBoro
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.