Check if all the characters in the list elements are letters

Viewed 44

Below is code to get all the list elements containing characters. Is there any efficient way of doing the same thing?

ls = ['1a', 'b3', '1.45', 'apples', 'oranges', 'mangoes', 'apples.', 'apples+', 1,456,1.3,'apples-1']
finalls=[]

for l in ls:
    try:
        if l.isalpha():
            finalls.append(l)
    except AttributeError as e:
        pass
        # if str(l).isdigit():
        #     print("element is isdigit", l)
            
print(finalls)

['apples', 'oranges', 'mangoes'] # Desired Ouput
3 Answers

First way:

ls = ['1a', 'b3', '1.45', 'apples', 'oranges', 'mangoes', 'apples.', 'apples+', 1,456,1.3,'apples-1']


new_lst = [a  for a in ls if str(a).isalpha()]
print(new_lst) 

second way


from string import ascii_lowercase as letter

ls = ['1a', 'b3', '1.45', 'apples', 'oranges', 'mangoes', 'apples.', 'apples+', 1,456,1.3,'apples-1']

new_lst = list(filter(lambda e:all(a in letter+letter.upper() for a in str(e)),ls))

OUtput

['apples', 'oranges', 'mangoes']

Update you code

Don't add try-except just convert the element to string then check if it contains all letters.

ls = ['1a', 'b3', '1.45', 'apples', 'oranges', 'mangoes', 'apples.', 'apples+', 1,456,1.3,'apples-1']
finalls=[]

for l in ls:
    if str(l).isalpha():
        finalls.append(l)
            
print(finalls)

Check the built-in filter function. It takes as first argument a function which is called for all elements and will yield only elements for which the function returns true.

For your example, this can be reduced to

ls = ['1a', 'b3', '1.45', 'apples', 'oranges', 'mangoes', 'apples.', 'apples+', 1,456,1.3,'apples-1']
finalls = list(filter(lambda e: isinstance(e, str) and e.isalpha(), ls))
print(finalls)

Note that you can iterate directly over the "result" of the filter function, you only need to convert it to a list if you really need the list. So a more typical example would not convert it to a list:

ls = ['1a', 'b3', '1.45', 'apples', 'oranges', 'mangoes', 'apples.', 'apples+', 1,456,1.3,'apples-1']
for fruit in filter(lambda e: isinstance(e, str) and e.isalpha(), ls)
    print(fruit)

Why not simply use a list comprehension?

finalls = [x for x in ls if isinstance(x, str) and x.isalpha()]

List comprehensions are very fast. They are also clear and easy to read.

Related