Search code examples
pythonlistlist-comprehension

Mixed type list comprehensions in Python


im trying to filter a list for numbers greater than a certain value whilst keeping any strings in the list.

Id like to acheive this without a loop, so preferably a list comprehension. So far i have this, i know why its not working but im unsure how to get it to work

my_list = [1, 2, 3, 'hello', 'world']
filtered_list = [x for x in my_list if (isinstance(x,str)) | ((isinstance(x,int))&(x>2))]

expected result:

[3, 'hello', 'world']

Actual result:

TypeError: '>' not supported between instances of 'str' and 'int'

Solution

  • You need to use logical operators. You can also reduce it to one isinstance using not

    filtered_list = [x for x in my_list if not (isinstance(x, int) and x < 3)]
    print(filtered_list) # [3, 'hello', 'world']