Removing all strings in a list that are of x length

Viewed 132

One of my revision practices involves creating a function that removes all strings that has the highest string length in a list.

Expected Output:

words_list = ['fish', 'barrel', 'like', 'shooting', 'sand', 'bank']
print(remove_long_words(words_list))
['fish', 'barrel', 'like', 'sand', 'bank']

Code so far:

def remove_long_words(words_list):
    length_long = get_longest_string_length(words_list)
    
    for ele in words_list:
        if len(ele) == length_long:
            #???
            words_list.pop(???)
    
    return words_list

I first made a function that returns the length of the longest string in the list, then used a for loop to iterate through every element in the list, and from there used an if statement to see if the length of the element is equal to the longest string length. I'm having trouble going on from there, how do I use the .pop method to remove the right elements from the list?

Do I have to convert the list to a string then use .find to find the index position of the element that meets the required length? And how would I make it that it finds all occurrences, not just the first one it finds.

4 Answers

Using a list comprehension:

words_list = ['fish', 'barrel', 'like', 'shooting', 'sand', 'bank']
max_len = len(max(words_list, key=len))
output = [x for x in words_list if len(x) != max_len]
print(output)  # ['fish', 'barrel', 'like', 'sand', 'bank']

Using Lambda function

words_list = ['fish', 'barrel', 'like', 'shooting', 'sand', 'bank']
list(filter(lambda x,m=max(map(len, words_list)):len(x)!=m, words_list))

Output

['fish', 'barrel', 'like', 'sand', 'bank']

There is a one-liner that you could use, but I find this easier to understand.

words_list = ['fish', 'barrel', 'like', 'shooting', 'sand', 'bank']
max = max(words_list, key=len)
list = []
for word in words_list:
    if len(word) < max:
        list.append(word)
print(list)

Since you're explicitly asking about list.pop You can first create masking for each item based on the length, and iterate through the index of this mask list and pop the elements:

maxLen = len(max(words_list))
mask = [len(x) == maxLen for x in words_list]

for i in reversed(range(len(mask))):
    if mask[i]:
        words_list.pop(i)

Make sure you pop in reversed order of index to avoid IndexError

OUTPUT

['fish', 'barrel', 'like', 'sand', 'bank']
Related