Data Types in Python – Explained with Examples

Data Types in Python – Explained with Examples. Python is an extremely powerful and popular programming language that is well known for its clear syntax, code readability, and ease of use.

The Python programming language is efficient such that you write complex programs with fewer lines of code than some other programming languages.

Many different industries use Python, from finance and data analysis to scientific computing and web development.

One of the best things about Python is that it is well documented and offers many different data types, making it easy to make a wide range of applications that work well.

In this article, we explore the full extent of data types in Python. Moreover, we review each category and data type to see how to use them and what data items you may store.

What are the Data Types in Python?

Data types are the foundation of programming. They let you specify the type of data you’re dealing with and how it needs to be handled.

Understanding data types is important because they define the structure and meaning of data. In addition, they determine what operations to perform on values of a particular type.

Moreover, data type identifiers are the keywords that are used to indicate different data types. For example, integers have a data type identifier of Int.

Hence, Python has many built-in data types for numbers, strings, and Boolean values. What is more, Python also gives you the option of creating your own custom data type.

Follow this post to learn data types in Python with relevant examples.

Data Types in Python - Explained with Examples

Python includes a lot of built-in data types. These data types are classified into a particular class as they define similar kinds of data. For example, numeric types cover all quantitative data.

But before we get into data types and categorization, take a look at the type function, which helps us identify the data type of the given data.

Identify Data Types in Python

The type function is used to identify the particular data type. It helps if you have forgotten the variable’s declared data type.

This function also comes in handy when the programmer needs to know the specific data type required to handle the given data.

In the following program, we have declared two variables with specific data. And we have used the type function to print the data types of these variables.

See that the type function will return the types of both variables in the output.

This function is repeatedly used in this tutorial for data type verification.

Text Type Data Types

This category primarily contains strings

Text Type Data Types

Strings

Strings are a collection of Unicode characters. They are like sequence type data types as they are essentially arrays of bytes representing Unicode characters, and you traverse them like arrays. But as they represent one cohesive data item, we consider them a separate category.

The single line string is declared with single or double quotes. But if you are defining a multiple line string, you have to use triple quotes.

				
					 # Python Program for
# Creation of String
 
# Creating a String with single Quotes
String1 = 'Hello World'
print(String1)
print(type(String1))
 
# Creating a String with double Quotes
String1 = "Hello World"
print(String1)
print(type(String1))

# Creating a String with triple Quotes allows multiple lines
String1 = '''Hello 
World'''
print(String1)
print(type(String1))
				
			

You see in the output that the triple quotes will save a multiple line string.

You also traverse the string data type using the different indexing methods. The first is traditional positive indexing, in which the position is specified from the beginning.

				
					# Python Program to Access
# characters of String
 
String1 = "Hello World"
print(String1)
 
# Printing First character
print("\nFirst character of String is: ")
print(String1[0])
 
# Printing Last character
print("\nLast character of String is: ")
print(String1[-1])
				
			

Negative indexing, on the other hand, allows negative address references to access characters from the back of the string; for example, -1 refers to the last character, -2 refers to the second previous character, and so on. 

Numeric Type Data Types

Three types of numeric data types offered by Python cover any kind of number, be it whole, decimal point, or complex number.

Int

The int data type is used to represent whole numbers. It accommodates any whole number, be it positive or negative.

Float

If a number contains a decimal or, more specifically, a floating point, you cannot use the int data type. The Float data type is designed to store numeric in such cases. The scientific number also falls into this category.

Complex

There are unique numbers with real and imaginary parts called complex numbers. Complex data types store such complex numbers. Keep in mind that the accompanying character j serves as a clue as to what the imaginary part is.

Note that you do typecasting or change the types of variables within numeric data types according to your needs. This becomes especially convenient when the result of the computation results in a float or complex number, or vice versa. 

Sequence Type Data Types

Lists

A list is a structured sequence of items. It is a widely used data type in Python due to its flexibility. It supports duplicates and mutable values.

				
					# Creating a List with
# the use of multiple values
List = ["apple","Mango","Lychee"]
 
# accessing a element from the
# list using index number
print("Accessing element from the list")
print(List[0])
print(List[2])

				
			

More importantly, alter these values later. Run the following lines with the code above. See the changes in the list .

				
					List = ["apple","Mango","grapes"]
print(List[2])
				
			

Tuple

A tuple also represents sequenced data, like a list. The main difference between these two is that the Tuple cannot be changed once it has been made.

				
					# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
print(type(Tuple3))

tuple1 = tuple([1, 2, 3, 4, 5])
# Accessing element using indexing
print("First element of tuple")
print(type(tuple1[0]))
				
			

Have multiple data types in the tuple, like lists and strings. You can even have nested tuples in a tuple.

Range

The range is a data type that generates a sequence with the default increment of 1. Define the lower and upper limits in the declaration.

Mapping Type Data Types

Dictionary

A dictionary represents the key-value pair of data items. A key-value pair refers to a constant key and variable value that are associated with each other.

A dictionary item is in a specific order and you cannot change or duplicate it.

See the following example to see how to declare and retrieve a specific dictionary using the key.

				
					dict = {"name" : "John", "age" : 36}

#display x:
print(dict)

#display x by key:
print(dict["name"])

#display the data type of x:
print(type(dict)) 

				
			

Programming uses this data type more frequently, as most real life data items are associates in the same way as the key value pair.

Set Data Type

As the name suggests, this data type is used to represent sets. Sets can save the unordered and unindexed data item collection. Consider the following example.

				
					x = {"apple", "banana", "cherry"}

#display x:
print(x)

#display the data type of x:
print(type(x)) 

#check for element in set
print("apple"in x)

#display the elements of x:
print("\nElements of set: ")
for i in x:
    print(i, end=" ")
				
			

See that you cannot directly display the data items from the set, You have to use a loop for that. Alternatively, you check for a specific element in the set.

Boolean Data Type

The Boolean data type has only two values: True or False. This data type is special because it evaluates expressions. Programmers use it to assess expressions and check whether the required conditions meet.

The Boolean variables are unique as they become the basis of program flow.

Binary Type Data Types

Python’s byte and byte array data types are used to manipulate binary data.

Memoryview is a buffer protocol that supports bytes and bytearray. The memoryview can access other binary data objects’ memory without copying the actual data.

See the following examples for their definition and extraction.

That’s it for the built in data types in Python and their examples.

Data Types in Python - Explained with Examples Conclusion

 Python is undeniably one of the most versatile programming languages out there. The number of data types Python offers, reflects this fact. For example, numeric, string, Boolean, lists, etc.

This article has discussed all the built in data types in Python. And multiple examples are given to aid your understanding of data types.

Explore our Python section to learn more.

Avatar for Sobia Arshad
Sobia Arshad

Information Security professional with 4+ years of experience. I am interested in learning about new technologies and loves working with all kinds of infrastructures.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x