-1

I have the current list

[['A', 'B', 'C'],
 ['A', 'B', 'D'],
 ['A', 'B', 'C', 'D'],
 ['A', 'C', 'D'],
 ['B', 'C', 'D']]

I want to delete the list ['A', 'B', 'C', 'D']. Is there any way to do this by checking inside the list and removing the list if it has more than 3 elements? Thanks

I know I could iterate over the whole list, and add the elements where the lenght is 3. But I don't think it is very efficient

TheObands
  • 378
  • 1
  • 3
  • 16

3 Answers3

2

Use a list comprehension!

[ x for x in array ]

will return the array as is. x represents an element in the array, in your case, the sub-arrays that you want to check the length of.

You can add a condition to this to filter:

[ x for x in array if ... ]

This will return the array but only for elements x that pass the condition after the if.

So you will want to check the length of x using the len function. In this case, your list comprehension should only include x when len(x) <= 3

In the spirit of learning I haven't given you the literal answer but you should be able to piece this information together.

Play around with list comprehensions, they are very powerful and constantly used in python to transform, map, and filter arrays.

Christopher Reid
  • 4,318
  • 3
  • 35
  • 74
0
b=[['A', 'B', 'C'],
 ['A', 'B', 'D'],
 ['A', 'B', 'C', 'D'],
 ['A', 'C', 'D'],
 ['B', 'C', 'D']]
c=[]
for i in b:  
    if len(i)<=3:
        print(i)
        c.append(i)
Suraj Shejal
  • 640
  • 3
  • 19
0

This script creates a new list by parsing through each index of the original list and getting the length of it. If the length is 3 then it gets added to the new table, if it doesn't have a length of 3 then it gets forgotten about

newlist = [] 
for a in range (0, len(oldlist)):
    if len(oldlist[a]) == 3:
        newlist.append(oldlist[a])