2

I was wondering if there were a way in python to loop through a list and check if a list element was of a certain type. Something like this in incorrect pseudo code.

listt = ['3109', datetime.timedelta(0, 240), datetime.timedelta(0, 60), '2411', 
datetime.timedelta(0, 2160), '3109']
for i in listt:
    if type(i) is class.__str__:
        print('success')

Is it possible to check for type like this? Also, I found myself unable to iterate through a list with timedelta objects so I've had to except a TypeError every time I encounter one. That is not shown in this code.

I appreciate any help. Thanks

2

3 Answers 3

4

You can do this using isinstance:

for i in listt:
    if isinstance(i,str):
        print('success')

Output:

success
success
success

Note that your pseudo code almost works. The following would work as well:

for i in listt:
    if type(i) is str:
        print('success')
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I can't believe I forgot about this.
I was getting a bit ahead of myself with the dunders.
3

Another isinstance way:

for i in listt:
    print(isinstance(i,str))

Saved one line, but result would be:

True
False
False
True
False
True

Comments

1

you can use the type() function.

a = 3.14
if type(a) == str:
     pass

More information can be found here:

How to determine a Python variable's type?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.