How to check the type of elements in a Python list?

Asked

Viewed 949 times

1

I have a list of data, and I need to verify that all elements are integer or string, or any other type of data. It is possible to verify all elements or needs to be one by one?

For example:

Lista = [0,1,2,3,4,5,6,"7"]

I need a function that tells me if they are all whole or not.

1 answer

3


  • Thank you for responding promptly. It worked, there is some case where this function cannot or should not be used?

  • There always is, but in general there is no problem. It will give problem in case it is not hers, but something collateral, so it would have to see the context.

  • I’m doing a function to calculate the checksum of a data packet to be sent in a serial form. Then I check the buffer size and if all the data is integer, so I can calculate the checksum and prepare the data to be sent.

  • In the case of a checksum, isinstance(dado, int) It might not be a good one - since you don’t just need integers - you need integers from 0 to 255 without a signal, each one repressing a byte. In this case, you can simply try to turn your list into an object of the type bytes or bytearray - if one of the values is out of range, this will cause an error. : sum(bytes(meus_dados))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.