TechBeamersTechBeamers
  • Viral Tips 🔥
  • Free CoursesTOP
  • TutorialsNEW
    • Python Tutorial
    • Python Examples
    • C Programming
    • Java Programming
    • MySQL Tutorial
    • Selenium Tutorial
    • Selenium Python
    • Playwright Python
    • Software Testing Tutorial
    • Agile Concepts
    • Linux Concepts
    • HowTo Guides
    • Android Topics
    • AngularJS Guides
    • Learn Automation
    • Technology Guides
  • Top Interviews & Quizzes
    • SQL Interview Questions
    • Testing Interview Questions
    • Python Interview Questions
    • Selenium Interview Questions
    • C Sharp Interview Questions
    • Java Interview Questions
    • Web Development Questions
    • PHP Interview Questions
    • Python Quizzes
    • Java Quizzes
    • Selenium Quizzes
    • Testing Quizzes
    • HTML CSS Quiz
    • Shell Script Quizzes
  • ToolsHOT
    • Python Online Compiler
    • Python Code Checker
    • C Online Compiler
    • Review Best IDEs
    • Random Letter Gen
    • Random Num Gen
TechBeamersTechBeamers
Search
  • Viral Tips 🔥
  • Free CoursesTOP
  • TutorialsNEW
    • Python Tutorial
    • Python Examples
    • C Programming
    • Java Programming
    • MySQL Tutorial
    • Selenium Tutorial
    • Selenium Python
    • Playwright Python
    • Software Testing Tutorial
    • Agile Concepts
    • Linux Concepts
    • HowTo Guides
    • Android Topics
    • AngularJS Guides
    • Learn Automation
    • Technology Guides
  • Top Interviews & Quizzes
    • SQL Interview Questions
    • Testing Interview Questions
    • Python Interview Questions
    • Selenium Interview Questions
    • C Sharp Interview Questions
    • Java Interview Questions
    • Web Development Questions
    • PHP Interview Questions
    • Python Quizzes
    • Java Quizzes
    • Selenium Quizzes
    • Testing Quizzes
    • HTML CSS Quiz
    • Shell Script Quizzes
  • ToolsHOT
    • Python Online Compiler
    • Python Code Checker
    • C Online Compiler
    • Review Best IDEs
    • Random Letter Gen
    • Random Num Gen
Follow US
© TechBeamers. All Rights Reserved.
Python Basic

Understand Data Types in Python

Last updated: Apr 18, 2025 4:27 pm
Meenakshi Agarwal
By
Meenakshi Agarwal
Meenakshi Agarwal Avatar
ByMeenakshi Agarwal
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large...
Follow:
No Comments
1 month ago
Share
16 Min Read
SHARE

Variables stores data and data types control the type of value they can store. This Python tutorial covers all the essential data types in Python. Just to know that Python uses dynamic typing meaning a variable’s type is determined at runtime.

Contents
Know Everything about Python Data TypesBoolean Data TypeNumber Data Type in PythonPython Strings Data TypeBytes Data Type in PythonPython Lists Data TypeTuples Data Type in PythonPython Set Data TypeDictionaries in PythonSummary: Different Data Types in Python
Python Data Types - Learn from Basic to Advanced

Know Everything about Python Data Types

We have here a very crisp and concise detail on the 8 data types. Please remember these are basic building blocks of Python programming. Hence, you must at least go through the optimal detail provided here.

Boolean Data Type

A boolean is such a data type that almost every programming language has, and so is Python. Boolean in Python can have two values – True or False. These are constants and can be used to assign or compare boolean values. Follow a simple example given below.

condition = False
if condition == True:
print("You can continue with the prpgram.")
else:
print("The program will end here.")

While making boolean conditions in Python, we can skip the explicit comparison in our code. And we’ll still get the same behavior.

condition = False
if condition:
print("You can continue with the prpgram.")
else:
print("The program will end here.")

The above code will yield the same output as the previous one due to the below statement

if condition:

is equivalent to,

if condition == True:

Next, an expression in Python can also produce a boolean result.

For example – The expression in a condition block will yield a boolean value. Python creates boolean contexts to evaluate expressions.

Whatever the expression is, Python will use the boolean context to determine its truth value. Since Python has many data types, it operates with its own rules to find the result in a boolean context.

str = "Learn Python"

print( len(str) )        # 12
print( len(str) == 12 )  # True
print( len(str) != 12 )  # False

In some cases, the boolean constants “True” and “False” might also act as numbers.

A, B = True + 0, False + 0
print(A, B)  # 1 0
print( type(A), type(B) )  # (<class 'int'>, <class 'int'>)

It is evident from the above example that True is 1 and the value of False is 0. And they will turn into numbers during arithmetic operations.

Number Data Type in Python

Numbers are one of the most prominent Python data types. Unlike many languages with only integers and floats, Python introduces complex as a new type of numbers.

Here are a few points for you to ponder.

  • The numbers in Python are classified using the following keywords: int, float, and complex.
  • Python has a built-in function type() to determine the data type of a variable or the value.
  • Another built-in function isinstance() is there for testing the type of an object.
  • In Python, we can add a “j” or “J” after a number to make it imaginary or complex.

Example.

num = 2
print("The number (", num, ") is of type", type(num))

num = 3.0
print("The number (", num, ") is of type", type(num))

num = 3+5j
print("The number ", num, " is of type", type(num))
print("The number ", num, " is complex number?", isinstance(3+5j, complex))
#Output
The number ( 2 ) is of type <class 'int'>
The number ( 3.0 ) is of type <class 'float'>
The number (3+5j) is of type <class 'complex'>
The number (3+5j) is complex number? True
  • We can create a complex number by using the type as a constructor. See the example below.
print( complex(1.2,5)) #(1.2+5j)
  • Integers in Python don’t have any size limitation as long as the required memory is available.
num = 1234567890123456789
print( num.bit_length() ) # 61
print( num ) # 1234567890123456789
num=1234567890123456789123456789012345678912345678901234567891234567890123456789
print( num.bit_length() ) # 250
print( num ) # 1234567890123456789123456789012345678912345678901234567891234567890123456789
  • A float-type number can have precision up to 15 decimal places.
import sys
print( sys.float_info )
# sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
print( sys.float_info.dig ) # 15

Python Strings Data Type

A string is treated as a sequence in Python. It is made up of one or more characters enclosed in quotes. Any letter, number, or symbol can also be part of a string. Another concept related to string is Python multiline string which requires a triple quotation mark at the start and one at the end.

str = 'A string wrapped in single quotes'
print( str ) # 'A string wrapped in single quotes'
str = "A string enclosed within double quotes"
print( str ) # 'A string enclosed within double quotes'
str = """A multiline string
starts and ends with
a triple quotation mark."""
print( str )
# 'A multiline string\nstarts and ends with\na triple quotation mark.'

Also, the strings in Python are immutable. It means the memory will be allocated once and re-used for further operations.

A = 'Python3'
print( id(A) ) # 140186214284656
B = A
print( id(B) ) # 140186214284656

You can see the second string shares the same address as the first one does.

Python has two popular versions, namely 2.7 and 3.4. Most programmers around the globe use either of them. The strings in Python 2 are by default non-Unicode (ASCII) but also have support for Unicode.

On the other hand, Python 3 strings are all Unicode (UTF-8).

Strings in Python 2

print(type('Python String'))  # <type 'str'>
print(type(u'Python Unicode String'))  # <type 'unicode'>

Strings in Python 3

print(type('Python String'))  # <class 'str'>
print(type(u'Python Unicode String'))  # <class 'str'>

Python allows slicing strings using a special square-bracket syntax to extract a substring. See the example below.

str = "Learn Python"
first_5_chars = str[0:5]
print(first_5_chars)  # Learn

substr_from_2_to_5 = str[1:5]
print(substr_from_2_to_5)  # earn

substr_from_6_to_end = str[6:]
print(substr_from_6_to_end)  # ython

last_2_chars = str[-2:]
print(last_2_chars)  # on

first_2_chars = str[:2]
print(first_2_chars)  # Le

two_chars_before_last = str[-3:-1]
print(two_chars_before_last)  # ho

Bytes Data Type in Python

The byte is an immutable type in Python. It can store a sequence of bytes (each 8-bit) ranging from 0 to 255. We can fetch the value of a single byte by using the index. But we can not modify the value. The following are a few differences between a byte and a string.

  • Byte objects contain a sequence of bytes whereas the strings store a sequence of characters.
  • The bytes are machine-readable objects whereas the strings are just in human-readable form.
  • Bytes are machine-readable and can be directly stored on the disk whereas strings need to be encoded before writing them to the disk.
# Make an empty bytes object (8-bit bytes)
empty_object = bytes(16)
print(type(empty_object))  # <class 'bytes'>
print(empty_object)
# b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

One scenario, where bytes matter is when carrying out I/O operations with buffering enabled. For example, we have a program that continuously receives data over the network. It parses the date after waiting for the message headers and terminators to appear in the stream. It keeps appending the incoming bytes to a buffer.

With Python byte object, it is easy to program the above scenario using the below pseudo code.

buf = b''
while message_not_complete(buf):
    buf += read_from_socket()

In the later sections of this tutorial, we’ll see the byte-to-string conversion and vice-versa.

Python Lists Data Type

Python list is an ordered sequence, similar to an array but can hold different types of objects. It is very flexible and supports dynamic sizing. The index in a list begins with a zero position. Here are some more points on it.

  • A list is a heterogeneous collection of items of varied data types. For example, a list object can store the files in a folder and the employee data in a company, etc.
  • Lists in Python are easy to create by placing elements inside square brackets separated by commas.
assorted_list = [True, False, 1, 1.1, 1+2j, 'Learn', b'Python']
first_element = assorted_list[0]
print(first_element)  # True
print(assorted_list)  # [True, False, 1, 1.1, (1+2j), 'Learn', b'Python']

for item in assorted_list:
    print(type(item))

"""
<class 'bool'>
<class 'bool'>
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>
<class 'bytes'>
"""
  • List objects are mutable. Python allows modifying a list or its elements via assignments and through the built-in list methods.
simpleton = ['Learn', 'Python', '2']
print( id(simpleton) )  # 56321160
print( simpleton )  # ['Learn', 'Python', '2']

simpleton[2] = '3'
print( id(simpleton) )  # 56321160

print( simpleton )  # ['Learn', 'Python', '3']
  • Interestingly, a list can contain another list. Such a list is called a nested list in Python.
nested = [[1,1,1], [2,2,2], [3,3,3]]
for items in nested:
    for item in items:
        print(item, end=' ')
		
# 1 1 1 2 2 2 3 3 3

Tuples Data Type in Python

A Python tuple is a heterogeneous collection of objects separated by commas. It means objects of different data types can co-exist in a tuple. The tuple and a list are somewhat similar as they share the following traits.

  • Both objects are a type of ordered sequence.
  • Each of them allows indexing and repetition.
  • Nesting is permitted.
  • They can store values of different types.

Below are some basic Python tuple examples.

# Defining a tuple without any element
pure_tuple = ()
print (pure_tuple)  # Output- ()

# Creating a tuple with nested tuples
first_tuple = (3, 5, 7, 9)
second_tuple = ('learn', 'python 3')
nested_tuple = (first_tuple, second_tuple)
print(nested_tuple)

# Creating a tuple with nested tuples
first_tuple = (3, 5, 7, 9)
second_tuple = ('learn', 'python 3')
nested_tuple = (first_tuple, second_tuple)
print(nested_tuple)

# Repetition in tuples
sample_tuple = ('Python 3',)*3
print(sample_tuple)

How is a tuple different than the list?

Tuples do differ a bit from the list as they are immutable. Python does not allow to modify a tuple after it is created. We can not add or remove any element later. Instead, Python expects us to create a new one with the updated sequence of elements.

Can a tuple have mutable objects as elements?

Here, comes the surprise. Modifying a tuple is forbidden. But Python doesn’t enforce it for the elements. It means we can update them if they are mutable objects.

Python Set Data Type

A Set is an unordered collection of unique and immutable objects. Its definition starts with enclosing braces { } having its elements separated by commas inside. Amongst all the Python data types, Set supports mathematical operations like union, intersection, symmetric difference, etc.

Python Set is similar to the “Set” in mathematics, hence it can’t have multiple occurrences of the same element.

What makes a Python set better than a list?

Python Set implements a highly optimized way to check whether it holds a specific element. This mechanism is known as a hash table.

To create a set, call the built-in set() function with a sequence or any iterable object.

sample_set = set("Python data types")
print( type(sample_set) ) # <class 'set'>
print( sample_set )
# {'e', 'y', 't', 'o', ' ', 'd', 's', 'P', 'p', 'n', 'h', 'a'}

Another simpler way is to specify the elements enclosed in curly braces {}.

another_set = {'red', 'green', 'black'}
print( type(another_set) ) # <class 'set'>
print( another_set) # {'red', 'green', 'black'}

What is a Frozen set in Python?

A frozen set is a processed form of the traditional set. It is immutable and only supports methods and operators that execute without altering the frozen set used in the context.

# An empty frozenset
print( frozenset() ) # frozenset()
cities = {"New York City", "Saint Petersburg", "London", "Munich", "Paris"}
fset = frozenset(cities)
print( type(fset) ) # <class 'frozenset'>

Read: How to check type of variable in Python

Dictionaries in Python

A dictionary in Python is an unordered collection of key-value pairs. It’s a built-in mapping type in Python where keys map to values. These key-value pairs provide an intuitive way to store data.

What is the need of a dictionary?

The dictionary solves the problem of storing a large data set. Python has made the dictionary object highly optimized for retrieving data.

Python syntax for creating dictionaries uses braces {} where each item appears as a pair of keys and values. The key and value can be of any Python data type.

sample_dict = {'key':'value', 'jan':31, 'feb':28, 'mar':31}
print( type(sample_dict) ) # <class 'dict'>
print( sample_dict )
# {'mar': 31, 'key': 'value', 'jan': 31, 'feb': 28}

How do you access dictionary elements with keys?

Dictionaries act like a database. Here, we don’t use a number to get a particular index value as we do with a list. Instead, we replace it with a key and then use the key to fetch its value.

Check: How to search keys in a Python dictionary

sample_dict = {'key':'value', 'jan':31, 'feb':28, 'mar':31}
print( sample_dict['jan'] ) # 31
print( sample_dict['feb'] ) # 28

Summary: Different Data Types in Python

This course covered the various Python data types and tried to explain them with examples. You may find all the relevant information here which can be useful for you in developing Python programs.

If you liked this tutorial, share it on your social media. Also, don’t forget to subscribe to our YouTube channel.

To learn Python more comprehensively, check out the following course which is again freely available.

Python Tutorial to Learn and Practice

Free Python Course for Beginners

Step-by-step Python course with 80+ tutorials, 20+ quizzes, and 100+ practice exercises.

100+Python Tutorials

Enjoy Coding,
TechBeamers

Related

Share This Article
Flipboard Copy Link
Subscribe
Notify of
guest

guest

0 Comments
Newest
Oldest
Inline Feedbacks
View all comments

List of Topics

Stay Connected

FacebookLike
XFollow
YoutubeSubscribe
LinkedInFollow

Subscribe to Blog via Email

Enter your email address to subscribe to latest knowledge sharing updates.

Join 1,011 other subscribers

Continue Reading

  • Python Operators GuideJan 15
  • Python Operator PrecedenceJan 17
  • Python Namespace ScopeFeb 4
  • Python Numbers GuideMar 6
  • Python SetMay 21
  • Python Exception HandlingAug 13
  • Python: 30 Programming Tips & TricksSep 18
  • Python Try-ExceptJun 16
  • Python Keywords, Identifiers, & VariablesJul 15
  • Python Statement & IndentationOct 30
View all →

RELATED TUTORIALS

Python List Count Method Explained with Examples

List Count Method

By Meenakshi Agarwal
1 month ago
Python List Index Method Explained with Examples

List Index Method

By Meenakshi Agarwal
1 month ago
python xrange vs. range function

Python XRange vs Range

By Meenakshi Agarwal
1 month ago
Python Strings to Integers - Check Out Practical Examples

Python Convert a String to an Integer

By Meenakshi Agarwal
1 month ago
© TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
wpDiscuz