Home > Back-end >  Python nested list conditional delete
Python nested list conditional delete

Time:12-12

I have a list of lists where some lists are not complete. I.e.:

data = [
['id1',1],
['id2'],
['id3'],
['id4'],
['id5',1]
]

I want to create a new list that contains only "full" lists.

Desired output:

[
['id1',1],
['id5',1]
]

I have tried:

new_data = [i for i in data if i[1]]

However, this returned:

List index error: Index out of range

I find it odd because the if[1] is right there.

Question

Is there a simple fix for a one-line approach, or must we use a for loop?

CodePudding user response:

Instead of trying accessing the values, check for length:

new_data = [i for i in data if len(i) == 2]
  • Related