Python is a versatile and powerful language that offers a multitude of possibilities for application development. Whether you are interested in system administration, building GUI programs, creating database applications, or even scripting, Python has got you covered. One of the critical strengths of Python lies in its extensive collection of data types in python, such as class ‘float, class ‘int, class ‘str, and frozen set, which enables efficient and effective implementation of a wide range of applications. Additionally, Python provides robust data structures like python list and python string, which are essential for handling data. Furthermore, understanding Python objects and their built-in functions will help you utilize the full potential of Python.
In this article, you will explore data types in Python with examples, learn how many data types exist in Python, delve into numeric data types in Python, and discover a handy Python data types cheat sheet for quick reference.
This article was published as a part of the Data Science Blogathon.
Data types in Python refer to classifying or categorizing data objects based on their characteristics and behavior. They determine the type of values variables can hold and specify the operations that can be performed on those values. For instance, Python has several built-in data types, including numeric types (int, float, complex), string (str), boolean (bool), and collection types (list, tuple, dict, set). Moreover, each data type has its own set of properties, methods, and behaviors that allow programmers to manipulate and process data effectively in their programs.
Python has several built-in data types that can be categorized into the following main groups:
Built-in data types in Python are fundamental data structures provided by the Python programming language. Pre-defined and available for use without requiring any additional libraries or modules. Python offers several built-in data types, including:
Checkout this article How to Learn Python and Here is Step-by Step Guide for Beginners
People use numeric data types in Python to represent numerical values. Python provides three primary numeric data types – integer (int), floating-Point (float) and complex (complex). These numeric data types allow for performing various arithmetic operations, such as addition, subtraction, multiplication, and division. They provide the necessary flexibility to work with numerical data in Python programs.
Python Code:
num1 = 10
print(num1)
print("Dtype of num1 is",type(num1))
fnum = 26.5
print(fnum)
print("Dtype of fnum is",type(fnum))
num3 = 2 + 6j
print(num3)
print('Dtype of num3 is',type(num3))
Python’s integer data type (int) represents whole numbers without any decimal points. It stores positive and negative whole numbers. Integers have immutability, meaning you cannot change their value once assigned.
Example1:
# Assigning integer values to variables
x = 5
y = -10
# Performing arithmetic operations
sum_result = x + y
difference_result = x - y
multiplication_result = x * y
division_result = x / y
# Printing the results
print("Sum:", sum_result)
print("Difference:", difference_result)
print("Multiplication:", multiplication_result)
print("Division:", division_result)
Output
Sum: -5
Difference: 15
Multiplication: -50
Division: -0.5
Example2:
# Using integer values in comparisons
a = 10
b = 20
# Comparing the values
greater_than = a > b
less_than_or_equal = a <= b
equal_to = a == b
not_equal_to = a != b
# Printing the results
print("Greater than:", greater_than)
print("Less than or equal to:", less_than_or_equal)
print("Equal to:", equal_to)
print("Not equal to:", not_equal_to)
Output:
Greater than: False
Less than or equal to: True
Equal to: False
Not equal to: True
In Python, people use the float datatype in python to represent floating-point numbers, which are numbers with decimal points. Floats offer more precision than integers when it’s needed. Floats are immutable like integers and follow the IEEE 754 standard for representing real numbers.
Example1:
# Assigning float values to variables
x = 3.14
y = 2.5
# Performing arithmetic operations
sum_result = x + y
difference_result = x - y
multiplication_result = x * y
division_result = x / y
# Printing the results
print("Sum:", sum_result)
print("Difference:", difference_result)
print("Multiplication:", multiplication_result)
print("Division:", division_result)
Output:
Sum: 5.64
Difference: 0.64
Multiplication: 7.85
Division: 1.256
Example2:
# Using float values in comparisons
a = 1.2
b = 2.7
# Comparing the values
greater_than = a > b
less_than_or_equal = a <= b
equal_to = a == b
not_equal_to = a != b
# Printing the results
print("Greater than:", greater_than)
print("Less than or equal to:", less_than_or_equal)
print("Equal to:", equal_to)
print("Not equal to:", not_equal_to)
Output:
Greater than: False
Less than or equal to: True
Equal to: False
Not equal to: True
In Python, people use the complex datatype in python to represent numbers with both real and imaginary parts. You write it in the form of a + bj, where a represents the real part and b represents the imaginary part. Complex numbers are useful in mathematical calculations and scientific computations that involve imaginary quantities.
Checkout this article about Mathematical Operations in Python with Numpy
Example1:
# Assigning complex values to variables
x = 2 + 3j
y = -1 + 2j
# Performing arithmetic operations
sum_result = x + y
difference_result = x - y
multiplication_result = x * y
division_result = x / y
# Printing the results
print("Sum:", sum_result)
print("Difference:", difference_result)
print("Multiplication:", multiplication_result)
print("Division:", division_result)
Output:
Sum: (1+5j)
Difference: (3+1j)
Multiplication: (-8+1j)
Division: (0.8-1.4j)
Example2:
# Using complex values in comparisons
a = 1 + 2j
b = 3 + 4j
# Comparing the values
equal_to = a == b
not_equal_to = a != b
# Printing the results
print("Equal to:", equal_to)
print("Not equal to:", not_equal_to)
Output:
Equal to: False
Not equal to: True
People use textual python data types in Python to represent and manipulate sequences of characters, such as words, sentences, or even larger blocks of text. The primary textual data type in Python is the string (str). You enclose strings in quotes (‘ ‘, ” “, or “”” “””) and can manipulate them using various string methods. They are immutable, meaning you cannot change their values once assigned. People commonly use string data types for tasks like text processing, input/output operations, and data manipulation.
Know More about Strings in Python For Beginners in this article!
You can express each character of a string using a technique called indexing. In indexing, each character has an index value represented by either a positive or negative integer starting from 0.
Syntax:- stringname[index]
Example1:
Str1=”Python
#accessing second character
Str1[1]
#accessing first four characters
Str1[0:4] # it will print the value from index 0 to 3
str1="Python"
>>> str1[1]
'y'
>>> str1[0:4]
'Pyth'
Positive indexing | 0 | 1 | 2 | 3 | 4 | 5 |
String | P | y | t | h | o | n |
Negative indexing | -6 | -5 | -4 | -3 | -2 | -1 |
Syntax:– str1 + str2
Example1:
>>> str1="Analytic"
>>> str2="Vidya"
>>> str3=str1 +str2
>>> print(str3)
AnalyticVidya
Syntax:– stringname * integervalue
Example2:
>>> str2 = "python"
>>> str2 * 3
'pythonpythonpython'
Syntax:– character in/not in stringname
Example3:
>>> str1="python"
>>> "p" in str1
True
>>> "f" in str1
False
Syntax:– len(stringname)
>>> str1="Python"
>>> len(str1)
6
Syntax:– stringname.isupper()
>>>str1= " Hello Everyone"
>>> str1.isupper()
False
>>> str2="HELLO"
>>> str2.isupper()
True
Syntax:– stringname.islower()
>>> s="hello"
>>> s.islower()
True
>>> s1="hey Folks!"
>>> s1.islower()
False
Syntax:– stringname.upper()
>>>str1= " Hello Everyone"
>>> str1.upper()
' HELLO EVERYONE'
Syntax:– stringname.lower ()
>>> str2="HELLO"
>>> str2.lower()
'hello'
The boolean python data types in Python represents logical values of True and False. Moreover, it is used to evaluate conditions and make logical decisions in a program. Additionally, Booleans are the result of comparisons and logical operations.
# Logical operations with booleans
a = True
b = False
result_and = a and b
result_or = a or b
result_not = not a
print(result_and)
print(result_or)
print(result_not)
Output:
False
True
False
# Comparisons using booleans
x = 5
y = 10
greater_than = x > y
less_than_or_equal = x <= y
equal_to = x == y
not_equal_to = x != y
print(greater_than)
print(less_than_or_equal)
print(equal_to)
print(not_equal_to)
Output:
False
True
False
True
Collection data types in Python are used to store and organize multiple values into a single entity. Python provides several built-in collection data types, including lists, tuples, dictionaries, and sets.
The list data type in Python is used to store multiple items in a single variable. Additionally, lists are ordered, mutable, and can contain elements of different data types. Specifically, they are created by enclosing comma-separated values within square brackets [ ].
List1=[123,567,89] #list of numbers
List2=[“hello”,”how”,”are”] #list of strings
List3= [“hey”,1223,”hello”] #list of mixed data type.
Elements of the list are accessed in the same as that of string that is with the help of positive and negative indexing. Slicing is also used to access the list elements in which more than a single element is accessed at a time.
List1=[“apple”,123,”mango”,[2,3,4,]]
Positive index | 0 | 1 | 2 | 3 |
List | “apple” | 123 | “mango” | [2,3,4] |
Negative index | -4 | -3 | -2 | -1 |
>>> list1=['apple',123,"mango",[2,3,4,]]
>>> list1[0]
'apple'
>>> list1[3]
[2, 3, 4]
>>> list1[1:3]
[123, 'mango']
Operations in List
Syntax:- list1 + list2
>>> list1=["apple","mango",123,345]
>>> list2 = ["grapes"]
>>> list1 + list2
['apple', 'mango', 123, 345, 'grapes']
Syntax:- list1* number
>>> list1=["apple","mango",123,345]
>>> list1*2
['apple', 'mango', 123, 345, 'apple', 'mango', 123, 345]
Syntax:– element in/not in in list1
>>> list1=["apple","mango",123,345]
>>> 'apple' in list1
True
>>> 'apple' not in list1
False
Built-in functions in the list
Syntax :- listname.append(element)
>>> list1=["apple","mango","grapes",123,345]
>>> list1.append("orange")
>>> list1
['apple', 'mango', 'grapes', 123, 345, 'orange']
>>> list1.append([12,34,55])
>>> list1
['apple', 'mango', 'grapes', 123, 345, 'orange', [12, 34, 55]]
Syntax :- listname.insert (index,element)
>>> list2=["apple","mango","grapes",123,345]
>>> list2.insert(0,234)
>>> list2
[234, 'apple', 'mango', 'grapes', 123, 345]
>>> list2.insert(6,"papapa")
>>> list2
[234, 'apple', 'mango', 'grapes', 123, 345, 'papapa']
Syntax:– listname.count(element)
>>> list3=[12,45,12,67,78,90]
>>> list3.count(12)
2
>>> list3.count(11)
0
Syntax:– listname.reverse()
>>> list3=[12,45,12,67,78,90]
>>> list3.reverse()
>>> list3
[90, 78, 67, 12, 45, 12]
Syntax:– listname.sort()
list4=["grapes","banana","apple","mango"]
>>> list4.sort()
>>> list4
['apple', 'banana', 'grapes', 'mango']
>>>list5=[12,45,12,67,78,90]
>>>list5.sort()
[12,12,45,67,78,90]
Dictionary is a special data type that is a mapping between a set of keys and a set of values. It represents a key-value pair enclosed in curly brackets, and each element is separated by a comma. Additionally, key-value pairs are separated by a colon. Furthermore, the elements of the dictionaries are unordered, and the key is unique for each value in the dictionary. The elements of the dictionary are mutable that is its elements can be changed once it is created.
Syntax:- Dictionaryname={key:value}
Example1:
Dict1={“comp”: “computer” , “sci” : “science”}
Dict2={“123”:”computer”,456 : “maths”}
The elements of the dictionary are accessed with the help of the keys. Each key serves as an index and maps the value in the dictionary.
Syntax:- dictionaryname[key]
>>> dict1={"comp": "computer" , "sci" : "science"}
>>> dict1["comp"]
'computer'
>>> dict1["sci"]
'science'
New elements are added in the dictionary with the help of a new key.
>>> dict1={"comp": "computer" , "sci" : "science"}
>>> dict1["comm"]="commerce"
>>> dict1
{'comp': 'computer', 'sci': 'science', 'comm': 'commerce'}
Syntax:- dictionaryname.items()
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> dict1.items()
dict_items([('comp', 'computer'), ('sci', 'science'), ('comm', 'commerce')])
Syntax:- dictionaryname.keys()
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> dict1.keys()
dict_keys(['comp', 'sci', 'comm'])
Syntax:- dictionaryname.values()
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> dict1.values()
dict_values(['computer', 'science', 'commerce'])
Syntax:- len(dictionaryname)
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> len(dict1)
3
Syntax:- dictionary1.update(dictionary2)
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> dict2={"acc":"accounts","bst":"business studies"}
>>> dict1.update(dict2)
>>> dict1
{'comp': 'computer', 'sci': 'science', 'comm': 'commerce', 'acc': 'accounts', 'bst': 'business studies'}
The set data type in Python is an unordered collection of unique elements. Therefore, people use it to store multiple items without any duplicates. You create sets by enclosing comma-separated elements within curly braces { } or by using the set() constructor.
# Creating a set
my_set = {1, 2, 3, 4, 5}
# Accessing elements
for element in my_set:
print(element)
# Checking membership
is_present = 3 in my_set
# Printing the results
print(my_set)
print(is_present)
Output:
1
2
3
4
5
{1, 2, 3, 4, 5}
True
# Set operations
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Union of sets
union = set1.union(set2)
# Intersection of sets
intersection = set1.intersection(set2)
# Difference of sets
difference = set1.difference(set2)
# Printing the results
print(union)
print(intersection)
print(difference)
Output:
Copy code
{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}
{1, 2, 3}
The tuple data type in Python is similar to a list but with one crucial difference: tuples are immutable. Once you create a tuple, you cannot modify its elements. You create tuples by enclosing comma-separated values within parentheses ( ).
# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)
# Accessing elements by index
first_element = my_tuple[0]
last_element = my_tuple[-1]
# Slicing a tuple
subset = my_tuple[1:4]
# Printing the results
print(my_tuple)
print(first_element)
print(last_element)
print(subset)
Output:
(1, 2, 3, 4, 5)
1
5
(2, 3, 4)
In Python, classes provide a way to define custom python data types. Specifically, classes encapsulate data and methods, thereby allowing for the creation of objects with specific attributes and behaviors. Moreover, classes serve as blueprints for creating objects. They define the structure and behavior of objects, including their attributes (data) and methods (functions). Consequently, objects are instances of classes, and each object has its own unique state and behavior.
Want to know about Methods about Python Checkout this article!
# Defining a class
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# Creating objects
point1 = Point(2, 3)
point2 = Point(5, 7)
# Accessing object attributes
print(point1.x, point1.y)
print(point2.x, point2.y)
Output:
2 3
5 7
# Defining a class with methods
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
# Creating an object and using methods
circle = Circle(5)
print(circle.area())
Output:
78.5
Python data types form the foundation of any Python programming endeavor. Therefore, understanding and utilizing these data types effectively is essential for developing robust and efficient applications. Consequently, by mastering the intricacies of Python data types, you will have the necessary skills to tackle complex programming challenges.
If you still have doubts and need help with Python concepts, enroll in our Introduction to Python Program.
Hope you like the article! In Python, there are different data types with examples like numbers (int
, float
, and complex
). There are about eight main data types in Python. Numeric data types in Python are important for doing math. A Python data types cheat sheet is a great tool for beginners to learn quickly.
A. Yes, a Python class is a data type.
In Python, everything is an object, and classes are the blueprints for creating these objects. So, a class defines a new type of data.
A. Integer (int)
Float (float)
String (str)
Boolean (bool)
List (list): Ordered collection, like [1, 2, 3].
Tuple (tuple): Ordered, immutable collection, like (1, 2, 3).
Set (set): Unordered collection of unique items, like {1, 2, 3}.
Dictionary (dict): Key-value pairs, like {“key”: “value”}.
A. Integer (int)
Float (float)
String (str)
List (list)
Dictionary (dict)
A. Python has several data types, but the main ones include the 8 primary types listed above (int, float, str, bool, list, tuple, set, dict). Additionally, Python supports complex numbers, bytes, byte arrays, and more, making it quite flexible.
Very well explained & helpful, really helps talking about what wash type is & then giving a simple example. I read this from my phone & see till gained a lot of knowledge. Thank you for writing this & your time.
Stumbled on this post by chance on google in my android. An tell you what, you what, you made my day! I've hearing that Python is an 'obvious syntax's language. Right now I have decided to go further and deep. I program in Matlab. So, why not compare the two.
if we have a large number, we can separate the millions, thousands, etc. with underscores: 42_000 is a valid int literal in recent versions of Python.