All Courses
Python Data Types

A Python data type is a classification or classification of data elements. It represents the type of value that indicates what you can do with specific data. Data types are actually classes, and variables are instances (objects) of those classes because everything is an object in Python programming.
Following are Python’s default or built-in data types:

  • Numeric
  • Sequence Type
  • Boolean
  • Set
  • Dictionary
Python Data Types

Numeric

At first, In Python, a numeric data type represents data that has a number. Then, the number can be an integer, a floating-point number, or a complex number. Finally, These values ​​are defined in Python as int, float, and complex classes.

  • Integer-This value is represented by the int class. Contains positive or negative integers (not fractions or decimals). In Python, there is no limit to the length of an integer value.
  • Float-This value is represented by the float class. The real number of the floating-point representation. A decimal point indicates float. You can optionally add a positive or negative integer after the letter e or E to indicate scientific notation.
  • Complex-Complex numbers are represented by complex classes. It is given as (real part) + (imaginary part) j. Example – 2 + 3j
Note-The type () function is used to determine the type of a data type.

For example, consider the following code:

# Python program to
# demonstrate numeric value

a = 7
print("Type of a: ", type(a))

b = 7.9
print("\nType of b: ", type(b))

c = 4 + 7j
print("\nType of c: ", type(c))

Output:

Type of a:  <class 'int'>

Type of b:  <class 'float'>

Type of c:  <class 'complex'>

Sequence Type

In Python, a sequence is an ordered collection of similar or dissimilar data types. Sequences allow you to store multiple values ​​in an organized and efficient way. There are several sequence types in Python they are:

  • String
  • List
  • Tuple

1. String

  • A string is a sequence of quoted characters. In Python, you can use single quotes, double quotes, or triple quotes to define a string.
  • Working with strings is a trivial task, as Python provides built-in functions and operators for performing operations on strings.
  • For string processing, the operation “hello” + “python” returns “hellopython“, so use the + operator to concatenate the two strings.
  • Using the * repeat operator, the operation “Python” * 2 returns “Python Python”.

The following example shows the Python string.

Example – 1

str = "string using double quotes"  
print(str)  
s = '''''A multiline 
string'''  
print(s)  

Output:

string using double quotes
A multiline
string

Consider the following example of string handling.

Example – 2

str1 = 'hello eMexo' #string str1    
str2 = ' how are you' #string str2    
print (str1[0:2]) #printing first two character using slice operator    
print (str1[4]) #printing 4th character of the string    
print (str1*2) #printing the string twice    
print (str1 + str2) #printing the concatenation of str1 and str2 

Output:

he
o
hello eMexohello eMexo
hello eMexo how are you

2. List

  • Python lists are similar to C arrays. However, the list can contain different types of data.
  • There are commas (,) between items in the list, and square brackets [] surround each item.
  • You can access the data in the list using the slice [:] operator.
  • The concatenation operator (+) and the repeat operator (*) operate on lists as they would for strings.

Consider the following example code:

list1  = [1, "hi", "Python", 2]    
#Checking type of given list  
print(type(list1))  
  
#Printing the list1  
print (list1)  
  
# List slicing  
print (list1[3:])  
  
# List slicing  
print (list1[0:2])   
  
# List Concatenation using + operator  
print (list1 + list1)  
  
# List repetation using * operator  
print (list1 * 3)  

Output:

[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

3. Tuple

  • Tuples are similar to lists in many ways. Like lists, tuples contain a collection of elements of various data types. Tuple elements are separated by commas (,) and enclosed in parentheses ().
  • Tuples are read-only data structures because you cannot change the size and value of the elements in the tuple.

Let’s look at a simple example code of a tuple:

tup  = ("hi", "Python", 2)    
# Checking type of tup  
print (type(tup))    
  
#Printing the tuple  
print (tup)  
  
# Tuple slicing  
print (tup[1:])    
print (tup[0:1])    
  
# Tuple concatenation using + operator  
print (tup + tup)    
  
# Tuple repatation using * operator  
print (tup * 3)     
  
# Adding value to tup. It will throw an error.  
t[2] = "hi"  

Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):
  File "main.py", line 14, in <module>
    t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Boolean

  • A data type that has either True or False two built-in values.
  • Then, Boolean objects equal to True are truthy (true) and objects equal to False are falsy (false).
  • However, non-Boolean objects can also be evaluated in a Boolean context and determined as true or false. This is indicated by the class bool.
Note – True and False, including the uppercase "T" and "F", are valid Boolean values. Otherwise, Python will throw an error.

For example, consider the following code:

# Python program to
# demonstrate boolean type

print(type(True))
print(type(False))

print(type(true))

Output:

<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
  File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in 
    print(type(true))
NameError: name 'true' is not defined

Set

  • A Python Set is an unordered collection of data types. It is repeatable, modifiable (modifiable after creation), and has its own elements.
  • The set does not define the order of the elements. You can return the changed order of the elements.
  • Sets are created using the built-in set () function, or a sequence of elements is passed in curly braces and separated by commas. It can contain different types of values.

For example, consider the following code:

# Creating Empty set  
set1 = set()  
  
set2 = {'eMexo', 2, 3,'Python'}  
  
#Printing Set value  
print(set2)  
  
# Adding element to the set  
  
set2.add(10)  
print(set2)  
  
#Removing element from the set  
set2.remove(2)  
print(set2) 

Output:

{3, 'Python', 'eMexo', 2}
{'Python', 'eMexo', 3, 2, 10}
{'Python', 'eMexo', 3, 10}

Dictionary

  • At first, A Python dictionary is an unordered collection of data values ​​used to store data values, like a map.
  • It contains key/value pairs, unlike other data types that hold only a single value as an element.
  • Key values ​​are provided to further optimize the dictionary.
  • Finally, Each key/value pair in the dictionary is separated by a colon: and each key is separated by a comma.

Creating Dictionary

At first, In Python, you can create a dictionary by arranging a series of items in curly braces {} separated by “commas”. Dictionary values ​​can be duplicated with any data type, but keys cannot be repeated and must be immutable. Dictionaries can also be created using the built-in function dict(). Finally, An empty dictionary can be created simply by enclosing it in curly braces {}.

Note-Dictionary keys are case sensitive and have the same name, but they are processed differently in different instances of the key.

For Example:

# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
	
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'eMexo', 2: 'For', 3: 'eMexo'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
	
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'eMexo', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
	
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'eMexo', 2: 'For', 3:'eMexo'})
print("\nDictionary with the use of dict(): ")
print(Dict)
	
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'eMexo'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)

Output:

Empty Dictionary: 
{}

Dictionary with the use of Integer Keys: 
{1: 'eMexo', 2: 'For', 3: 'eMexo'}

Dictionary with the use of Mixed Keys: 
{1: [1, 2, 3, 4], 'Name': 'eMexo'}

Dictionary with the use of dict(): 
{1: 'eMexo', 2: 'For', 3: 'eMexo'}

Dictionary with each item as a pair: 
{1: 'eMexo', 2: 'For'}

Accessing elements of the Dictionary

At first, To access a dictionary element, see its key name. Then, Keys can be used in square brackets. There is also a method called get () that also helps you access items from the dictionary.

For Example:

# Python program to demonstrate
# accessing a element from a Dictionary
	
# Creating a Dictionary
Dict = {1: 'eMexo', 'name': 'For', 3: 'eMexo'}
	
# accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])

# accessing a element using get()
# method
print("Accessing a element using get:")
print(Dict.get(3))

Output:

Accessing a element using key:
For
Accessing a element using get:
eMexo