Juul
Juul

Reputation: 1

Test the length of elements in a list

def lengthgood(x):
    for i in x:
        if len(i)<13
            return i
        else:
            pass


def makeproperlist(x):
    return x.split(',')



attendancelist=makeproperlist(input("attendee list:"))
final_list=list(filter(lengthgood,attendancelist))
for i in finallist:
    print (i)

I want to write a programme of which I create a list in which only elements shorter than 14 can be a part of.

This is my code, but it keeps returning all the elements I put in, even if some of them are longer than 14?

I tried to print the len(i) and it says that it is 1 for every element in the list?

How do I solve this?

Upvotes: 0

Views: 262

Answers (3)

kaleem231
kaleem231

Reputation: 357

You want to create a list but you not define it anywhere in program simply done it with simply one function makeproperlist(x).
Try this code bro this will help you.

attendancelist=[]
while (True):
   ch=input("Enter c for continue and e for exit : ")
   if (ch=='c'):
       def makeproperlist(x):
           if x<=13:
               attendancelist.append(x)
           else:
               print("Enter number which is <= to 13.")
       makeproperlist(int(input("attendee list:")))
    elif (ch=='e'):
        break;
print("Your attendece list : ",attendancelist)

Upvotes: 0

Andrey Topoleov
Andrey Topoleov

Reputation: 1919

may be like that

flst = []

def croper(lst):
    for i in lst:
        flst.append(i) if len(i) < 13 else 0 


lst = input("attendee list:").split(',')
croper(lst)

print(flst)

or shorter

def croper(lst):
    return [i for i in lst if len(i) < 13] 

lst = input("attendee list:").split(',')

print(croper(lst))

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191733

You shouldn't put a return within a loop; it'll only return the first element that matches your condition.

You also shouldn't be looping within your filter function, because you're actually looping over characters of strings, which are all length 1.

Therefore, the first character is always returning a truthy value, giving you back the initial input after filtering


You only need to check the input length, and filter functions should ideally return appropriate boolean conditions rather than truthy values (in your case return i is returning a non-empty string)

def lengthgood(x):
    return len(x)<13

If you don't need to use filter(), you can write a list comprehension

final_list=[a if len(a) < 13 for a in attendancelist] 

Upvotes: 2

Related Questions