Python Data Types with Examples

Nishtha Last Updated : 21 Nov, 2024
13 min read

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.

Learning Outcomes

  • Learn to manipulate mutable sequences of bytes using the bytearray type.
  • Perform arithmetic operations and manage floating-point numbers with float.
  • Execute integer-specific operations and understand the use of int in Python.
  • Handle text data and string operations using the str class effectively.
  • Use lists for ordered collections and learn methods for list manipulation in Python.
  • Perform a variety of operations on strings, a core sequence type in Python.
  • Understand the various sequence types like lists, strings, and bytearrays, and their use cases.
  • Access beginner-friendly tutorials to build a strong foundation in Python programming.
  • Explore NumPy for efficient numerical computations and handling large data arrays.

This article was published as a part of the Data Science Blogathon.

What are Data Types in Python?

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.

How many Data Types in Python?

Python has several built-in data types that can be categorized into the following main groups:

Numeric Types

  • int: Integers (whole numbers)
  • float: Floating-point numbers (decimal numbers)
  • complex: Complex numbers

Sequence Types

  • list: Ordered collection of items
  • tuple: Ordered, immutable collection of items
  • range: Sequence of numbers

Text Sequence Type

  • str: Sequence of Unicode characters (strings)

Mapping Type

  • dict: Unordered collection of key-value pairs

Set Types

  • set: Unordered collection of unique items
  • frozenset: Immutable version of a set

Boolean Type

  • bool: Represents either True or False

Binary Sequence Types

  • bytes: Immutable sequence of 8-bit integers
  • bytearray: Mutable sequence of 8-bit integers
  • memoryview: Provides a view of a bytes-like object

Built-in Data Types in Python

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:

  • Numeric Data Types: Numeric data types in Python are used to represent numerical values. Python provides three primary numeric datatype in python:
    1. Integer (int): Integers are whole numbers without any decimal points. They can be positive or negative.
    2. Floating-Point (float): Floating-point numbers represent decimal values. They can be positive or negative and may contain a decimal point.
    3. Complex (complex): People use complex numbers to represent numbers with a real and imaginary part. You write them in the form of a + bj, where a is the real part and b is the imaginary part.
  • String Data Type(str): Represents a sequence of characters enclosed in single quotes (‘ ‘) or double quotes (” “), such as “Hello, World!”, ‘Python’.
  • Boolean Data Type(bool): Represents either True or False, used for logical operations and conditions.
  • Collection Data Types:
    1. list: Represents an ordered and mutable collection of items, enclosed in square brackets ([]).
    2. tuple: Represents an ordered and immutable collection of items, enclosed in parentheses ().
    3. dict: Represents a collection of key-value pairs enclosed in curly braces ({}) with unique keys.
    4. set: Represents an unordered and mutable collection of unique elements, enclosed in curly braces ({}) or using the set() function.

Checkout this article How to Learn Python and Here is Step-by Step Guide for Beginners

Numeric Data Types

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.

  • Int – It stores the integers values that can be positive or negative and do not contain any decimal point. Example: num1=10, num2 = 15
  • Float – These are floating-point real numbers that stores the decimal values. It consists of integer and fraction parts. Example: fnum = 25.4, fnum1=67.8
  • Complex – These are complex numbers specified as a real part and an imaginary part. They are stored in the form of a + bj where a is the real part and j represents the imaginary part. Example: num3= 2 + 3j, numcom = 5 – 7j

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))

Integers (int)

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

Floating-Point Numbers (float)

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

Complex Numbers (complex)

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

Textual Data Types – Strings

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!

Accessing String Values

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

String Operations

  • Concatenation: Python allows us to join two different strings using the concatenation operator ‘+’ 
Syntax:– str1 + str2

Example1:

>>> str1="Analytic"
>>> str2="Vidya"
>>> str3=str1 +str2
>>> print(str3)
AnalyticVidya
  • Repetitions: Python allows us to repeat a given string with the help of ‘ * ‘ operator.
Syntax:– stringname * integervalue

Example2:

>>> str2 = "python"
>>> str2 * 3
'pythonpythonpython'
  • Membership: The Membership operator helps to check whether a given character is present in the string or not with the help of two operators in and not in. In and not in operator returns the boolean value True or False.
Syntax:– character in/not in stringname

Example3:

>>> str1="python"
>>> "p" in  str1
True
>>> "f" in str1
False

Built-in Functions in String

  • Len() – It is used to calculate the length of the given string.
Syntax:– len(stringname)
>>> str1="Python"
>>> len(str1)
6
  • isupper() – The function r() checks whether all the letters in a string are in the upper case or not. If all the characters are in upper case then it returns True otherwise it returns False.
Syntax:– stringname.isupper()
>>>str1= " Hello Everyone"
>>> str1.isupper()
False
>>> str2="HELLO"
>>> str2.isupper()
True
  • islower() – This function is used to check whether all the letters in a string are in lowercase or not. If all the characters are in lower case then it returns True otherwise it returns False.
Syntax:– stringname.islower()
>>> s="hello"
>>> s.islower()
True
>>> s1="hey Folks!"
>>> s1.islower()
False
  • upper() – It is used to convert all the characters of a string in uppercase.
Syntax:– stringname.upper()
>>>str1= " Hello Everyone"
>>> str1.upper()
' HELLO EVERYONE'
  • lower() – It is used to convert all the characters of a string in lowercase.
Syntax:– stringname.lower ()
>>> str2="HELLO"
>>> str2.lower()
'hello'

Boolean Data Type

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

# 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

# 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

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.

Lists (list)

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.

Accessing Elements of the List

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

  • Concatenation: Two lists are concatenated with the help of “+” operator.
Syntax:- list1 + list2
>>> list1=["apple","mango",123,345]
>>> list2 = ["grapes"]
>>> list1 + list2
['apple', 'mango', 123, 345, 'grapes']
  • Repititions: With the help of the ‘ * ‘ operator list can be repeated n number of times.
Syntax:- list1* number
>>> list1=["apple","mango",123,345]
>>> list1*2
['apple', 'mango', 123, 345, 'apple', 'mango', 123, 345]
  • Membership: ‘ in ‘and ‘ not in ‘ are two membership operators that are used to check whether the given element is present in the list or not and return a Boolean value True or False.
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

  • append(): This function is used to add a single element at the end of the list. The single element that is added can be of any python data types like integer, list, string, etc.
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]]
  • insert(): insert() function is also used to add element in this list but with the help of insert we can add the element at a particular index in the list. If the index is not present then it will add the element at the end of the list.
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']
  • count(): count function is used to count the number of time an element occurs in the list.
Syntax:– listname.count(element)
>>> list3=[12,45,12,67,78,90]
>>> list3.count(12)
2
>>> list3.count(11)
0
  • reverse(): reverse function is used to reverse the order of elements in the list.
Syntax:– listname.reverse()
>>> list3=[12,45,12,67,78,90]
>>> list3.reverse()
>>> list3
[90, 78, 67, 12, 45, 12]
  • sort(): sort function is used to arrange the elements of the list in ascending order. The function list must contain all the elements in the same data type that is either integers or strings.
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

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”}

Accessing Elements of the Dictionary

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'}

Built-in Functions in the Dictionary

  • items(): items() function returns a list of tuples of key-value pair of the dictionary.
Syntax:- dictionaryname.items()
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> dict1.items()
dict_items([('comp', 'computer'), ('sci', 'science'), ('comm', 'commerce')])
  • keys(): This function returns the list of keys in the dictionary.
Syntax:- dictionaryname.keys()
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> dict1.keys()
dict_keys(['comp', 'sci', 'comm'])
  • values(): It returns the list of values in the dictionary.
Syntax:- dictionaryname.values()
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> dict1.values()
dict_values(['computer', 'science', 'commerce'])
  • len(): length function is used to count the total number of elements in the dictionary.
Syntax:- len(dictionaryname)
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> len(dict1)
3
  • update(): It appends the key-value pair of the dictionary passed as the argument to the key-value pair of the given dictionary.
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'}

Sets (set)

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.

Set creation and accessing elements

# 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

# 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}

Tuples (tuple)

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 ( ).

Tuple creation and accessing elements

# 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)

Custom Data Types in Classes

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!

Creating a class and instantiating objects

# 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

Adding methods to a class

# 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

Conclusion

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 (intfloat, 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.

Key Takeaways

  • NumPy provides powerful capabilities for numerical computations, including support for large, multi-dimensional arrays and matrices.
  • Python 3 introduced several improvements and features over Python 2, making it the preferred version for modern development.
  • Everything in Python is an object, including numbers, strings, and functions, each with attributes and methods.
  • Understanding the type of data is crucial in Python for appropriate operations and method applications.
  • Use underscores to separate words in Python variable names (e.g., my_variable_name) for better readability
  • Using descriptive and consistent variable names enhances code readability and maintainability.

Frequently Asked Questions

Q1. Is a Python class a data type?

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.

Q2. What are the 8 data types in Python?

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”}.

Q3. What are the 5 standard data types in Python?

A. Integer (int)
Float (float)
String (str)
List (list)
Dictionary (dict)

Q4. How many data types are in Python?

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.

Responses From Readers

Clear

Shane Welcher
Shane Welcher

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.

Bawe Gerard Nfor Jr
Bawe Gerard Nfor Jr

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.

Narendra
Narendra

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.

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details