Delete elements of a list that do not have the same length as the majority of the entries

Viewed 177

I know how to delete an element in a list when it does not have a certain size like:

x = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2],[1,2,3],[1,2,3],[1,2,3,4]]
y = [s for s in x if len(s) == len(x[0])]

Where x is the original list, and y is the new list. As you can see in the first one there is one entry which is not as long as the others, and one which is longer then the others.

I want to delete an element each time it does not have the same length as the majority of elements in the list. The showed approach works as long as the first element in the list has the same length as the majority of the elements.

So the question is how to get the most common length of the elements? Without a loop iterating over the length. The mean will not work, because the mean will not represent the majority of length but the mean length of elements (e.g. lengths 3,3,3,30 will give a mean of ~ 10, while the majoritiy of lengths is 3.)

2 Answers
Related