Remove only strings from a list

Asked

Viewed 115 times

1

I have the following code:

Lista_1 = [10, 3, 6, 27, 'Maria']
Lista_2 = [37, 8, 45, 80, 'Jose']
Lista_3 = [43, 67, 99, 3.456, 'Pipoca']
Lista_4 = [432, 456, 333, 538, 'Bala']

Concatenating lists

Lista_Total = Lista_1 + Lista_2 + Lista_3 + Lista_4
[10, 3, 6, 27, 'Maria', 37, 8, 45, 80, 'Jose', 43, 67, 99, 3.456, 'Pipoca', 432, 456, 333, 538, 'Bala']

How could I remove only the str of that concatenated list? Or order by type and remove them?

2 answers

2

To know if a variable is a string, use the function isinstance, as already explained in reply from Fernando. Then just scroll through the list and disregard the elements that are strings:

Lista_Total = [ i for i in Lista_Total if not isinstance(i, str) ]
print(Lista_Total)

The result is the list:

[10, 3, 6, 27, 37, 8, 45, 80, 43, 67, 99, 3.456, 432, 456, 333, 538]

In this case, I used the syntax of comprehensilist on, much more succinct and pythonic.

It basically goes through the list and creates another list, containing only elements that are not strings. At the end, the result is assigned to the variable Lista_Total.

But if you want, you can make one for traditional. The code below is equivalent, generating the same list as the previous code:

lista_sem_strings = []
for i in Lista_Total:
    if not isinstance(i, str):
        lista_sem_strings.append(i)

At the end of loop, lista_sem_strings will be a list of all elements that are not strings.

1

To check if a variable is of type string you must use the function isinstance() and compare it with basestring in the case of Python 2.x and str for Python 3. Python example 2.7:

>>> isinstance('foo', basestring)
True
>>> isinstance(123, basestring)
False

To delete elements from the list you can do several ways. I think the easiest to understand would be to go in reverse and remove those that isinstance(x, basestring) for True. For the case of Python 2.7:

for i in reversed(range(len(Lista_Total))):
    if isinstance(Lista_Total[i], basestring):
        del Lista_Total[i]

If you still want to order it by type, just order it:

Lista_Total.sort()

Python naturally compares integers with strings and put the numbers before the strings.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.