5. Data Types

By | September 29, 2021

Built-in Data Types

In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type:str
Numeric Types:intfloatcomplex
Sequence Types:listtuplerange
Mapping Type:dict
Set Types:setfrozenset
Boolean Type:bool
Binary Types:bytesbytearraymemoryview

Getting the Data Type

You can get the data type of any object by using the type() function:

Example

Print the data type of the variable x:

x = 5
print(type(x))

Output:
<class ‘int’>

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

ExampleData TypeOutput
x = “Hello World”
display x:
print(x)
display the data type of x:
print(type(x))
strHello World
<class ‘str’>
x = 20int20
<class ‘int’>
x = 20.5float20.5
<class ‘float’>
x = 1jcomplexlj
<class ‘complex’>
x = [“apple”, “banana”, “cherry”]list[‘apple’, ‘banana’, ‘cherry’]
<class ‘list’>
x = (“apple”, “banana”, “cherry”)tuple(‘apple’, ‘banana’, ‘cherry’)
<class ‘tuple’>
x = range(6)rangerange(0, 6)
<class ‘range’>
x = {“name” : “John”, “age” : 36}dict{‘name’: ‘John’, ‘age’: 36}
<class ‘dict’>
x = {“apple”, “banana”, “cherry”}set{‘banana’, ‘apple’, ‘cherry’}
<class ‘set’>
x = frozenset({“apple”, “banana”, “cherry”})frozensetfrozenset({‘banana’, ‘apple’, ‘cherry’})
<class ‘frozenset’>
x = TrueboolTrue
<class ‘bool’>
x = b”Hello”bytesb’Hello’
<class ‘bytes’>
x = bytearray(5)bytearraybytearray(b’\x00\x00\x00\x00\x00′)
<class ‘bytearray’>
x = memoryview(bytes(5))memoryview<memory at 0x0368AFA0>
<class ‘memoryview’>

Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

ExampleData TypeTry it
x = str(“Hello World”)
display x:
print(x)
display the data type of x:
print(type(x))
strHello World
<class ‘str’>
x = int(20)int20
<class ‘int’>
x = float(20.5)float20.5
<class ‘float’>
x = complex(1j)complexlj
<class ‘complex’>
x = list((“apple”, “banana”, “cherry”))list[‘apple’, ‘banana’, ‘cherry’]
<class ‘list’>
x = tuple((“apple”, “banana”, “cherry”))tuple(‘apple’, ‘banana’, ‘cherry’)
<class ‘tuple’>
x = range(6)rangerange(0, 6)
<class ‘range’>
x = dict(name=”John”, age=36)dict{‘name’: ‘John’, ‘age’: 36}
<class ‘dict’>
x = set((“apple”, “banana”, “cherry”))set{‘cherry’, ‘banana’, ‘apple’}
<class ‘set’>
x = frozenset((“apple”, “banana”, “cherry”))frozensetfrozenset({‘cherry’, ‘apple’, ‘banana’})
<class ‘frozenset’>
x = bool(5)boolTrue
<class ‘bool’>
x = bytes(5)bytesb’\x00\x00\x00\x00\x00′
<class ‘bytes’>
x = bytearray(5)bytearraybytearray(b’\x00\x00\x00\x00\x00′)
<class ‘bytearray’>
x = memoryview(bytes(5))memoryview<memory at 0x01368FA0>
<class ‘memoryview’>

Leave a Reply

Your email address will not be published. Required fields are marked *