0

my task today is to create a function which takes a list of string and an integer number. If the string within the list is larger then the integer value it is then discarded and deleted from the list. This is what i have so far:

def main(L,n):

    i=0
    while i<(len(L)):
        if L[i]>n:
            L.pop(i)
        else:
            i=i+1
    return L

    #MAIN PROGRAM
    L = ["bob", "dave", "buddy", "tujour"]
    n = int (input("enter an integer value)
    main(L,n)

So really what im trying to do here is to let the user enter a number to then be compared to the list of string values. For example, if the user enters in the number 3 then dave, buddy, and tujour will then be deleted from the list leaving only bob to be printed at the end.

Thanks a million!

2
  • 2
    L = [i for i in L if len(i) <= n] Commented Mar 12, 2015 at 19:15
  • All the solutions posted were very helpful. Thanks, I really appreciate it! Commented Mar 12, 2015 at 19:25

4 Answers 4

1

Looks like you are doing to much here. Just return a list comprehension that makes use of the appropriate conditional.

def main(L,n):
    return([x for x in L if len(x) <= n])
Sign up to request clarification or add additional context in comments.

1 Comment

This creates a new list which is not the same as the OP's code
0

Just use the built-in filter method, where n is the cut off length:

newList = filter(lambda i:len(i) <= n, oldList)

Comments

0

You should not remove elements from a list you are iterating over, you need to copy or use reversed:

L = ["bob", "dave", "buddy", "tujour"]
n = int(input("enter an integer value"))

for name in reversed(L):
    # compare length of name vs n
    if len(name) > n:
        # remove name if length is > n
        L.remove(ele)
print(L)

Making a copy using [:] syntax:

   for name in l[:]:
        # compare length of name vs n
        if len(name) > n:
            # remove name if length is > n
            L.remove(ele)
    print(L)

Comments

0

This is a simple solution where you can print L after calling the main function. Hope this helps.

def main(L,n): l=len(L) x=0 while x<l: #if length is greater than n, remove the element and decrease the list size by 1 if len(L[x])>n: L.remove(L[x]) l=l-1 #else move to the next element in the list else: x=x+1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.