Python Data Types
Contents
2.5. Python Data Types#
Difination: Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data.
Python has the following data types built-in by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
2.5.1. Obtaining the Data Type#
You can get the data type of any object by using the type() function:
# Example:
x = 5
print(type(x))
<class 'int'>
2.5.2. Data Type Setting#
When you give a variable a value in Python, the data type is already determined:
x = "Hello World" # str
print(type(x))
<class 'str'>
x = 20 # int
print(type(x))
<class 'int'>
x = 20.5 # float
print(type(x))
<class 'float'>
x = 1j # complex
print(type(x))
<class 'complex'>
x = ["apple", "banana", "cherry"] # list
print(type(x))
<class 'list'>
x = ("apple", "banana", "cherry") # tuple
print(type(x))
<class 'tuple'>
x = range(6) # range
print(type(x))
<class 'range'>
x = {"name" : "John", "age" : 36} # dict
print(type(x))
<class 'dict'>
x = {"apple", "banana", "cherry"} # set
print(type(x))
<class 'set'>
x = frozenset({"apple", "banana", "cherry"}) # frozenset
print(type(x))
<class 'frozenset'>
x = True # bool
print(type(x))
<class 'bool'>
x = b"Hello" # bytes
print(type(x))
<class 'bytes'>
x = bytearray(5) # bytearray
print(type(x))
<class 'bytearray'>
x = memoryview(bytes(5)) # memoryview
print(type(x))
<class 'memoryview'>
2.5.3. Specifying a Particular Data Type#
The following function Object() { [native code] } functions can be used to indicate the data type:
x = str("Hello World") # str
print(type(x))
<class 'str'>
x = int(20) # int
print(type(x))
<class 'int'>
x = float(20.5) # float
print(type(x))
<class 'float'>
x = complex(1j) # complex
print(type(x))
<class 'complex'>
x = list(("apple", "banana", "cherry")) # list
print(type(x))
<class 'list'>
x = tuple(("apple", "banana", "cherry")) # tuple
print(type(x))
<class 'tuple'>
x = range(6) # range
print(type(x))
<class 'range'>
x = dict(name="John", age=36) # dict
print(type(x))
<class 'dict'>
x = set(("apple", "banana", "cherry")) # set
print(type(x))
<class 'set'>
x = frozenset(("apple", "banana", "cherry")) # frozenset
print(type(x))
<class 'frozenset'>
x = bool(5) # bool
print(type(x))
<class 'bool'>
x = bytes(5) # bytes
print(type(x))
<class 'bytes'>
x = bytearray(5) # bytearray
print(type(x))
<class 'bytearray'>
x = memoryview(bytes(5)) # memoryview
print(type(x))
<class 'memoryview'>