-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
  • 358
  • 2
  • 13
  • 3
    Use a list comprehension that checks `len(element)` – Barmar Oct 13 '20 at 22:59
  • 3
    StackOverflow is not a free coding service. You're expected to [try to solve the problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users). Please update your question to show what you have already tried in a [mcve]. For further information, please see [ask], and take the [tour] :) – Barmar Oct 13 '20 at 23:00
  • or if you are a beginner use a loop that checks the each element of the larger list and keeps it if it satisfies your condition – gold_cy Oct 13 '20 at 23:00

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
  • 3,938
  • 2
  • 30
  • 69
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
  • 628
  • 1
  • 17
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])