user1443707
user1443707

Reputation: 1

Remove all strings from list of strings and integers

You are given: list1 = [2, "berry", "joe", 3, 5, 4, 10, "happy", "sad"]

want to return [2, 3, 5, 4, 10]

Is it possible to remove just the strings from the list?

Upvotes: 0

Views: 104

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169524

Using a list-comprehension you can construct another list with just the elements you want.

>>> list1 = [2, "berry", "joe", 3, 5, 4, 10, "happy", "sad"]
>>> [i for i in list1 if isinstance(i, int)]
[2, 3, 5, 4, 10]

Alternative in case for example you also have floats and wish to keep those, too:

>>> list1 = [2, "berry", "joe", 3, 5, 4, 10.0, "happy", "sad"]
>>> [i for i in list1 if not isinstance(i, str)]
[2, 3, 5, 4, 10.0]

Upvotes: 1

Related Questions