1

How can i write the code for an if condition where i want to see if i can convert the type of an element in a list to int. If its possible, then if condition should be executed.Otherwise, it should go to else statement

For eg:

lst=['@','#','^','%','20']

''' Now i am going to iterate through the list and check if i can convert the elements  to type int. If it can be converted then i know there is a number in the list and i do some operations on the number'''

for ele in lst:
    if(type(int(ele)=='int'):
        #do some operation on the number eg:20/2 and print the value
    else:
        continue

Please give me an idea as to how to write the if condition.

2

4 Answers 4

1

Try to convert to int and catch the error:

for ele in lst:
    try:
        val = int(ele)
    except ValueError:
        continue
    else:
        print(val)
Sign up to request clarification or add additional context in comments.

Comments

0

You could check if each element is an int using a try block in a helper function is_int:

def is_int(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False

lst = ['@', '#', '^', '%', '20']
for s in lst:
    if is_int(s):
        int_s = int(s)
        print(f'{int_s}/2 = {int_s/2}')
    else:
        continue

Output:

20/2 = 10.0

Comments

0

Try with .isdigit()+a list comprehension (perfect couple ;-):

lst=['@','#','^','%','20']
[str(x).isdigit() for x in lst]

Caveat: does not work for float strings, for floats:

[str(x).replace('.','').isdigit() for x in lst]

Comments

0

I think what you are looking for is :

if isinstance(ele,int)
lst = ['@', '#', '^', '%', 20]

for ele in lst:
    if isinstance(ele,int):
        print("This is int: " + str(ele))
    else:
        print("This is not int: " + ele)

Very simple and easy.

2 Comments

Thank you. But I am checking if the elements can be converted to int type. not if the element is of type int.
Oh sorry about that :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.