How to remove all strings from a list of tuples python

Viewed 849

I am trying to remove all strings from a list of tuples

ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD'), (40, 'EEE')]

I have started to try and find a solution:

output = [i for i in ListTuples if i[0] == str]

print(output)

But I can't seem to get my head around how I would get an output like:

[(100), (80), (20), (40), (40)]

The format is always (int, str).

5 Answers

Use a nested tuple comprehension and isinstance:

output = [tuple(j for j in i if not isinstance(j, str)) for i in ListTuples]

Output:

[(100,), (80,), (20,), (40,), (40,)]

Note that there are trailing commas in the tuples to distinguish them from e.g. (100) which is identical to 100.

Since extracting the first item of each tuple is sufficient, you can unpack and use a list comprehension. For a list of tuples:

res = [(value,) for value, _ in ListTuples]  # [(100,), (80,), (20,), (40,), (40,)]

If you need just a list of integers:

res = [value for value, _ in ListTuples]     # [100, 80, 20, 40, 40]

For a functional alternative to the latter, you can use operator.itemgetter:

from operator import itemgetter
res = list(map(itemgetter(0), ListTuples))   # [100, 80, 20, 40, 40]

Here's another solution using filter():

def non_string(x):
    return not isinstance(x, str)

print([tuple(filter(non_string, x)) for x in ListTuples])
# [(100,), (80,), (20,), (40,), (40,)]

Try this

ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD'), (40, 'EEE')]

ListInt = []
ListStr = []

for item in ListTuples:
    strAux = ''
    intAux = ''
    for i in range(0, len(item)):

        if(isinstance(item[i], str)):
            strAux+=item[i] 
        else:
            intAux+=str(item[i])


    ListStr.append(strAux)
    ListInt.append(intAux)


print(ListStr)

'''TO CONVERT THE STR LIST TO AN INT LIST'''
output= list(map(int, ListInt)) 
print(output)

The output is [100, 80, 20, 40, 40]

We check if a particular value is a string or not using type(value).

output = [tuple([j for j in i if type(j)!=str]) for i in ListTuples]
print(output)
    [(100,), (80,), (20,), (40,), (40,)]
Related