How to remove all alphanumeric elements from the list in Python?

Here in this tutorial, you will learn how to remove all alphanumeric elements from the list in Python. Here in our tutorial, let us do this using isalnum(). We can also do this using regular expressions and isalpha(), isnumeric(). Most importantly, we use isalnum() because it is the easiest way to delete alphanumeric elements from the list.

Let us now see how to delete all alphanumeric elements from the list.

Python program to remove alphanumeric elements from the list

The alphanumeric elements mean the characters which have only alphabets, only numbers or a combination of both. The special characters don’t belong to alphanumeric elements.

isalnum()

The isalnum() is the special method in Python programming language. It returns True if all the characters are alphanumeric.

Have a look at the Python code below:




l=['kk','()','30','yhj','-','/','_','gh45','90']
for w in l:
   if not w.isalnum():
        print(w)

The above program will give the output that you can see below:

() 
-
 / 
_

When you want to print all alphanumeric characters from the list, the code is similar to the above one.
So, let us see the code now.

a=['kk','()','30','yhj','-','/','_','gh45']
for w in a:
   if w.isalnum():
        print(w)

It will give the following output:

kk
30
yhj
gh45

Now, let us have a look at the code when we use isalpha() and isnumeric().

k=['hi','()','30','hello','-','/','_','>','&']
for s in k:
   if not s.isalpha():
        if not s.isnumeric():
           print(s)

OUTPUT:

()
-
/
_
>
&

isalpha() and isnumeric()

These are the built-in methods in python.
These are used to know the presence of alphabets and numbers in a string.
The isalpha() method returns True if all characters are alphabets and the method isnumeric() returns True if all the characters are numbers.

Let us now see the example in using these methods.

a=['hi','()','30','hello','-','/','_']
for u in a:
   if u.isalpha():
        print(u)
        print(type(u))

OUTPUT:

hi
<class 'str'>
hello
<class 'str'>

Now, let us see an example for numbers.

a=['78','()','30','hello','-','/','_']
for w in a:
   if w.isnumeric():
        print(w)
        print(type(w))

OUTPUT:

78
<class 'str'>
30
<class 'str'>

Also, read:

 


Leave a Reply

Your email address will not be published. Required fields are marked *