python data types

In this tutorial, we will take a look at the Python Data Types. We will cover different categories of data types and conversions between them. By the end, we will know what these types of objects look like and how to represent them using Python.

What is a Data Type in Python?

In the Python programming language, everything is an object, and data types are classes. The objects of these classes are called variables. Variables are reserved memory locations for storing values. This means that when we create a variable, we reserve some space in memory. Based on the data type of the variable, the interpreter allocates memory and decides what can be stored in the reserved memory: integers, decimal numbers, or characters. Data types are a crucial concept in Python. It helps us understand what operations can be performed on a value.

Categories of Python Data Types

Python supports a number of common data types, each of which has a method for storing it. The data types specified in Python are listed below:

python data types

The type() function can be used to determine which class a variable or value belongs to. Similarly, the is instance() method determines if an object belongs to a specific class. Let’s look at each Data Type separately.

Numeric Type

A numeric data type in Python represents data with a numeric value. An integer, float, or complex number can all be used to represent a numeric value. Python defines these values as int, float, and complex classes.

Integer

This data type is represented using the int class. It consists of positive or negative integers (no fractions or decimals). Let’s assign to a variable integer and check its type and specific class:

# Assigning integer to the variable x
x = 100
# Printing the type of x using type()
print("The type of x -", type(x))
# Printing specific class of x using isinstance()
print("x is an integer -", isinstance(100,int))

Output:

The type of x - <class 'int'>
x is an integer - True

Float

This type is represented by the float class. It is a true floating-point number. It is denoted by the decimal point. Here is the example of assigning to a variable float and checking its type and specific class:

# Assigning float to the variable y
y = 69.69

# Printing the type of y using type()
print("The type of y -", type(y))
# Printing specific class of y using isinstance()
print("y is a float -", isinstance(69.69,float))

Output:

The type of y - <class 'float'>
y is a float - True

Complex Numbers

A complex number is represented by a complex class. It is defined as (real part) + (imaginary part)j. Let’s see an example of using complex numbers in Python:

# Assigning complex number to the variable z
z = 9+3j

# Printing the type of the z using type()
print("The type of z -", type(z))

# Printing specific class of x using isinstance()
print("z is a complex number -", isinstance(9+3j,complex))

Output:

The type of z - <class 'complex'>
z is a complex number - True

Dictionary Type

A dictionary is an unordered collection of elements that each include a key-value pair. The key can be any primitive data type, and the value can be any Python object. A dictionary is built by enclosing a list of items in curly braces ( {} ) and separating them with a comma. The built-in dict() method may also be used to generate a dictionary. Values in the dictionary can be of any data type and replicated, however, keys cannot be duplicated and must be immutable. Let’s see an example of dictionary using different Data Types:

# Creating an empty dictionary
Dict = {}
print("Empty dictionary:",Dict)

# Creating a dictionary with integer keys
Dict = {1:'Dictionary', 2:'with', 3:'Integers'}
print("\nDictionary with integer keys:", Dict)

# Creating a dictionary with mixed keys
Dict = {'Name':'Ages', 1:[27, 18, 13, 40]}
print("\nDictionary with mixed keys:", Dict)

# Using dict() function to create a dictionary
Dict = dict([(1, 'Dictionary'), [2, 'with'], [3,'Dict()']])
print("\nDictionary with dict() function:", Dict)

# Creating a dictionary with each item as a pair
Dict = dict([(1, 'One'), (2, 'Two')])
print("\nDictionary with each item as a pair:", Dict)

Output:

Empty dictionary: {}

Dictionary with integer keys: {1: 'Dictionary', 2: 'with', 3: 'Integers'}

Dictionary with mixed keys: {'Name': 'Ages', 1: [27, 18, 13, 40]}

Dictionary with dict() function: {1: 'Dictionary', 2: 'with', 3: 'Dict()'}

Dictionary with each item as a pair: {1: 'One', 2: 'Two'}

Boolean Type

The Boolean type provides two built-in values, True and False, used to determine whether a given statement is true or false. They are denoted by the bool class. True can be represented by any non-zero value or ‘T’, while false can be represented by 0 or ‘F’. Consider the following example:

# Assigning True to x
x = True

# Printing x's data type and class
print('x\'a data type is',type(x))
print('x\'s class is boolean -',isinstance(x,bool))

# Assigning False to y
y = False

# Printing x's data type and class
print('\ny\'s data type is',type(y))
print('y\'s class is boolean -',isinstance(y,bool))

Output:

x'a data type is <class 'bool'>
x's class is boolean - True

y's data type is <class 'bool'>
y's class is boolean - True

Set Type

A set is an unordered collection of data that can be iterated, modified, and has no duplicate elements. The order of elements in a set is undefined, and can consist of different elements of mixed data types. Sets can be created using the built-in set() function with an iterable object or sequence, placing the sequence inside curly braces ( {} ) separated by commas ( , ). Let’s use different methods to create sets:

# Creating an exmpty set using set() function
set1 = set()
print("Empty set:",set1)

# Creating a set with numbers using {}
set2 = {1, 11, 9.790, 1000}
print("\nSet with numbers:",set2)

# Creating a set with strings
set3 = set("GooDNighT")
print("\nSet with string:",set3)

# Creating a mixed set
set4 = set([1, 2, 'Water', 4, 'with', 6, 'lEmon'])
print("\nSet with mixed values",set4)

Output:

Empty set: set()

Set with numbers: {1000, 1, 11, 9.79}

Set with string: {'i', 'g', 'N', 'T', 'h', 'D', 'o', 'G'}

Set with mixed values {1, 2, 4, 'with', 6, 'Water', 'lEmon'}

Sequence Type

In Python sequences is a general term for an ordered set, which means that the order in which we enter elements will be the same when we access them. Python supports several different types of sequences. We will discuss strings, lists and tuples.

String

A string is a set of one or more characters surrounded by single, double or triple quotes, which are Unicode characters. There is no special character data type in Python; a character is also a string of only one length. The str class is used to represent strings. The following example shows a string:

# Creating a variable with string
string = 'Hello to Python!'

# Printing string's data type
print(string)
print('Type of string-',type(string))

Output:

Hello to Python!
Type of string- <class 'str'>

List

A list is an ordered sequence of elements. The declaration of a list is quite simple. Elements separated by commas are enclosed in brackets [ ]. A list can have any number of elements, and they can be of different types. The list is very flexible, which means that we can make different modifications over them. Let’s see example of list in Python:

# Creating lists with different type of values

list1 = [1,2,3,4]
print('List with integers only -',list1)
print('Type of list1 is',type(list1))

list2 = ['red','yellow','green']
print('\nList with strings only -',list2)
print('Type of list2 is',type(list2))

list3 = ['hello', 100, 3.14, [1,2,3] ]
print('\nList with mixed values -',list3)
print('Type of list3 is',type(list3))

Output:

List with integers only - [1, 2, 3, 4]
Type of list1 is <class 'list'>

List with strings only - ['red', 'yellow', 'green']
Type of list2 is <class 'list'>

List with mixed values - ['hello', 100, 3.14, [1, 2, 3]]
Type of list3 is <class 'list'>

Tuple

A tuple, like a list, is an ordered sequence of items. It is represented by the tuple class. The sole distinction between tuples and lists is that tuples are immutable, which means they cannot be modified once formed. Tuples are used to prevent data from being rewritten, and they are often quicker than lists. They are defined usually with or sometimes without parenthesis (), with items separated by commas. An empty tuple must be enclosed in brackets (). A comma must be used at the end of a tuple with only one element. Here is the example of tuples in Python:

# Creating atuple with mixed values
Tuple = (20,69,14.5,"green",14+8j)

# Printing tuples values and its class
print('Our tuple is',Tuple)
print('Class of Tuple', type(Tuple))

Output:

Our tuple is (20, 69, 14.5, 'green', (14+8j))
Class of Tuple <class 'tuple'>

Conversion between Data Types

It was all about Python Data Types. Now when we’re familiar with them let’s take a look how to convert between different Data Types. There are various built-in functions for converting data from one type to another.Usually to convert between types, we use the type name as a function. These functions produce a new object that represents the transformed value: int(), float(), complex(), str(), tuple(), list(), set(), dict(),etc. Let’s now use those functions to convert value of one Data Type to another.

# Creating a variable, then printing it with its type
x = 13.78
print(x,'-',type(x))

# Converting the variable to integer
x = int(x)
print('\n',x,'-',type(x))

# Converting the variable to float
x = float(x)
print('\n',x,'-',type(x))

# Converting the variable to complex number
x = complex(x)
print('\n',x,'-',type(x))

# Converting the variable to string
x = 13.78
x = str(x)
print('\n',x,'-',type(x))

# Converting the variable to tuple
x = tuple(x)
print('\n',x,'-',type(x))

# Converting the variable to list
x = list(x)
print('\n',x,'-',type(x))

# Converting the variable to set
x = set(x)
print('\n',x,'-',type(x))

Output:

 13.78 - <class 'float'>

 13 - <class 'int'>

 13.0 - <class 'float'>

 (13+0j) - <class 'complex'>

 13.78 - <class 'str'>

 ('1', '3', '.', '7', '8') - <class 'tuple'>

 ['1', '3', '.', '7', '8'] - <class 'list'>

 {'.', '1', '7', '8', '3'} - <class 'set'>

Conclusion

In this tutorial we learned about different Python Data Types, covered their categories, and practiced creating a variable with one Data Type and changing from one type to another.

Leave a Reply

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