Macintosh Fan
Macintosh Fan

Reputation: 405

How to check if an integer or string exists in a list

I want to know how I can check if an integer is in a list. Here is some code I made:

# "1" is a string. 10 is an integer.
my_list = ["1", 10]
if int in my_list:
    print("Integer in the list!")

What is wrong with this code? And how do I make it work?

Upvotes: 0

Views: 2500

Answers (3)

Abhinash
Abhinash

Reputation: 1

U can use this code to check type: b=[10,20,'apr','str','abh','cdf'] for i_dex,i in enumerate(b): if isinstance(i,str): print(f'{i} is str') else: print(f'{i} is int')

Upvotes: 0

Brian61354270
Brian61354270

Reputation: 14433

As mentioned by Cargcigenicate, both int == "1" and int == 10 are False, so the overall check is False. What you want to do is check whether or not an element in the list is an instance of int, not whether or not they are equal to int.

This can be accomplished a bit more concisely by using the builtin any along with a generator expression:

if any(isinstance(x, int) for x in my_list):
    ...

Note that in general using isinstance should be prefered over type when reasoning about the type of an object since the former takes inheritance into account.

Upvotes: 3

Carcigenicate
Carcigenicate

Reputation: 45750

The problem with this is, int == 10 is false. int is a class, and 10 is an instance of the class. That doesn't mean however that they equate to each other.

You'd need to do some preprocessing first. There's many ways to do this, and it ultimately depends on what your end goal is, but as an example:

my_list = ["1", 10]

# Create a new list that holds the type of each element in my_list
types = [type(x) for x in my_list]

if int in types:  # And check against the types, not the instances themselves
    print("Integer in the list!")

Upvotes: 1

Related Questions