Python Forum
Removing all strings in a list that are of x length
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Removing all strings in a list that are of x length
#1
Hey all,

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.
Reply


Messages In This Thread
Removing all strings in a list that are of x length - by Bruizeh - May-04-2021, 04:52 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Removing existing tuples from a list of tuple Bruizeh 4 2,808 May-15-2021, 07:14 PM
Last Post: deanhystad
Question Recursion and permutations: print all permutations filling a list of length N SantiagoPB 6 3,345 Apr-09-2021, 12:36 PM
Last Post: GOTO10
  Removing items in a list cap510 3 2,356 Nov-01-2020, 09:53 PM
Last Post: cap510
  How do you find the length of an element of a list? pav1983 13 4,928 Jun-13-2020, 12:06 AM
Last Post: pav1983
  list of strings to list of float undoredo 3 2,708 Feb-19-2020, 08:51 AM
Last Post: undoredo
  Removing items from list slackerman73 8 4,462 Dec-13-2019, 05:39 PM
Last Post: Clunk_Head
  Convert a list of integers to strings? Cornelis 3 2,284 Nov-15-2019, 12:13 PM
Last Post: perfringo
  Print The Length Of The Longest Run in a User Input List Ashman111 3 3,226 Oct-26-2018, 06:56 PM
Last Post: gruntfutuk
  List of Strings Problem jge047 3 3,641 Dec-19-2017, 04:06 AM
Last Post: dwiga
  need help removing an item from a list jhenry 4 4,214 Oct-13-2017, 08:15 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020