Python Data Types and Type Conversion
An introduction on Python data types and how to perform type conversions.
Python Data Types
When we create or declare variables in Python, the variables can hold different data types.
Python has the following built-in data types:
- str
- int, float, complex
- list, tuple
- dict
- set
- bool
- byte, bytearray
Text Type: str
The str
data type is used when we want to declare a string variable.
Example:
x = "some string"
y = str("another string")
Numeric Type: int, float, complex
When we want to create numeric variables we use int
, float
or complex
.
Example:
//int
a = 5
b = int(5)
//float
c = 5.5
d = float(5.5)
//complex
e = 1j
f = complex(1j)
Sequence Type: list, tuple
To create sequence type variables we use list
or tuple
.
- A
list
is a collection which is ordered and changeable. Allows duplicate members. - A
tuple
is a collection which is ordered and unchangeable. Allows duplicate members.
Example:
//list
colors = ['red', 'green', 'blue']
colors_list = list(('red', 'green', 'blue'))
//tuple
fruits = ('apple', 'orange', 'banana')
fruits_tuple = list(('apple', 'orange', 'banana'))
Mapping Type: dict
To create a map or dictionary we use dict
.
A Dictionary is a collection which is unordered, changeable and indexed. The data are key value pairs.
Example:
people = {"name": "John", "age": "45"}
people_dict = dict(name="John", age=45)
Set Type: set
A set
is a collection which is unordered and not indexed.
To create a set, we use set
.
Example:
status_codes = {"200", "300", "400", "500"}
status_codes = set(("200", "300", "400", "500"))
Boolean Type: bool
The bool
keyword is used to create variables with boolean data type.
is_valid = False
valid = bool(is_valid)
Binary Type: byte, bytearray
Binary data types can be created as follows:
//bytes
a = b"some_text"
b = bytes(5)
//bytearray
c = bytearray(3)
How to get the Type of a Variable
To get the type of a variable we wrap the variable inside the type()
function.
For example:
colors = ['red', 'green', 'blue']
colors_list = list(('red', 'green', 'blue'))
print(type(colors_list))
print(colors_list)
fruits = ('apple', 'orange', 'banana')
fruits_tuple = tuple(('apple', 'orange', 'banana'))
print(type(fruits_tuple))
print(fruits_tuple)
Output:
<class 'list'>
['red', 'green', 'blue']
<class 'tuple'>
('apple', 'orange', 'banana')
Python Data Type Conversion
Python defines type conversion functions to directly convert one data type to another, which is quite useful.
Below are some examples:
Convert From int to float
x = 5
y = float(x)
print(y)
Output:
5.0
Convert From float to int
x = 5.0
y = int(x)
print(y)
Output:
5
Convert From string to list
s = "devqa"
t = list(s)
print(t)
Output:
['d', 'e', 'v', 'q', 'a']
Convert From string to tuple
s = "devqa"
t = tuple(s)
print(t)
Output:
('d', 'e', 'v', 'q', 'a')
Convert From string to set
s = "devqa"
t = set(s)
print(t)
Output:
{'d', 'e', 'a', 'v', 'q'}