TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: 8 Most Important Python Data Types to Know
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

8 Most Important Python Data Types to Know

Last updated: Nov 23, 2023 11:15 am
By Meenakshi Agarwal
Share
18 Min Read
Python Data Types - Learn from Basic to Advanced
Python Data Types - Learn from Basic to Advanced
SHARE

In this tutorial, you will learn about the different data types in Python. Data types define the kind of value that a variable can store and the operations that can be performed on that value. Python uses dynamic typing, which means that the data type of a variable is determined at runtime.

Contents
1. Boolean Data Type2. Number Data Type in Python3. Python Strings Data Type4. Bytes Data Type in Python5. Python Lists Data Type6. Tuples Data Type in Python7. Python Sets Data Type8. Dictionaries in Python

Here is Everything You Need to Know

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 we have provided here.

1. 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 values 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 will operate 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.

2. Number Data Type in Python

Numbers are one of the most prominent Python data types. Unlike many languages which have 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
  • To form a complex number, we can even use 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

3. 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 thereafter.

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

4. 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. Similar to an array, we can fetch the value of a single byte by using the index. But we can not modify the value.

Here 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 is continuously receiving 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.

5. 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, or 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

6. 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.

If you somehow have not read 100+ Python interview questions from our blog, consider checking them out. They are a great resource for anyone who is preparing for a Python interview or wants to improve their Python skills.

7. Python Sets 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 is one that 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 data type has a significant advantage over a list. It implements a highly optimized method that checks whether the container hosts a specific element or not. The mechanism used here is based on a data structure 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'>

8. 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.

Why need a dictionary?

The dictionary solves the problem of efficiently 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}

Accessing 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.

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

Methods to access dictionary elements

Python exposes the following built-in dictionary functions.

  • keys() – It isolates the keys from a dictionary.
  • values() – It isolates the values from a dictionary.
  • items() – It returns the items in a list style of (key, value) pairs.
sample_dict = {'key':'value', 'jan':31, 'feb':28, 'mar':31}
print( sample_dict.keys() )
# dict_keys(['mar', 'key', 'jan', 'feb'])

print( sample_dict.values() )
# dict_values([31, 'value', 31, 28])

print( sample_dict.items() )
# dict_items([('mar', 31), ('key', 'value'), ('jan', 31), ('feb', 28)])

Modifying a dictionary (Add/update/delete)

Since the dictionary object is mutable, we can call add, update, and delete operations on a dictionary object. See the below example for more clarity on how to modify a dictionary.

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

sample_dict.update({'apr':30})
print( sample_dict )
# {'apr': 30, 'mar': 31, 'key': 'value', 'jan': 31, 'feb': 29}

del sample_dict['key']
print( sample_dict )
# {'apr': 30, 'mar': 31, 'jan': 31, 'feb': 29}

Apart from learning about the data types, you should also know the different operators in Python. Furthermore, check out one of our recent additions about the xor operator in Python.

Conclusion

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

If you find something new to learn today, then do share it with others. And, follow us on our social media accounts to see more such tutorials.

Best,

TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
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 MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python Comment, Multiline Comment, & DocString Python Comment vs Multiline Comment
Next Article Python Operators Tutorial for Beginners to Learn Python Operators – A Practical Guide for Beginners

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x