len, type, isinstance

Type and length checking

Interview Relevant: Fundamental functions

len, type, isinstance

Check length and types.

Code Examples

Type and length checking.

python
1# len - get length
2len([1, 2, 3])    # 3
3len("hello")      # 5
4len({"a": 1})     # 1
5
6# type - get exact type
7type(42)          # <class 'int'>
8type("hello")     # <class 'str'>
9type([1, 2])      # <class 'list'>
10
11# type checking (not recommended)
12type(x) == int    # Works but...
13
14# isinstance - preferred for type checking
15isinstance(42, int)           # True
16isinstance("hi", str)         # True
17isinstance([], (list, tuple)) # Check multiple types
18
19# issubclass - check class inheritance
20issubclass(bool, int)  # True
21
22# Custom class
23class Animal: pass
24class Dog(Animal): pass
25isinstance(Dog(), Animal)  # True

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In