Last modified: Jan 10, 2023 By Alexander Williams
Remove Intger From a List in Python [Good Exapmles]
In this tutorial, we'll learn how to remove integers from a list.
Before getting started, let's see the list that we are going to use in this tutorial.
[1, '2050', 'hello', 50, 'python', 2006]
If you look carefully, you'll see that we have:
3 strings: '2050', 'hello', 'python'
3 integers: 1, 50, 2006
And now, let's get started.
Remove integer from a list using the isinstance() method.
To remove the integer form list, we need to follow these steps:
- Iterate over the list.
- Check the type of each item by using the isinstance() method.
- If the item is not an integer, we'll append it to a new list.
Let's see the example:
my_list = [1, '2050', 'hello', 50, 'python', 2006]
new_list = []
for i in my_list:
if not isinstance(i, int):
new_list.append(i)
print(new_list)
output
['2050', 'hello', 'python']
Now, let's do it in the sort syntax.
new_list = [i for i in my_list if not isinstance(i, int)]
print(new_list)
output
['2050', 'hello', 'python']
Remove integer from a list using the using type()
Instead of isinstance(), we can use the type() method.
Let's see an example.
new_list = []
for i in my_list:
if type(i) is not int:
new_list.append(i)
print(new_list)
output
['2050', 'hello', 'python']
Let's write the code in the sort syntax.
new_list = [i for i in my_list if type(i) is not int]
print(new_list)
output
['2050', 'hello', 'python']