PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python Data Types

Python Data Types

Updated on: September 26, 2022 | 8 Comments

Data types specify the different sizes and values that can be stored in the variable. For example, Python stores numbers, strings, and a list of values using different data types.

Table of contents

  • Str data type
    • Example
  • Int data type
    • Example
    • Example
  • Float data type
    • Example
  • Complex data type
    • Example
  • List data type
    • Example list creation and manipulation
  • Tuple data type
    • Example Tuple creation and manipulation
  • Dict data type
    • Example dictionary creation and manipulation
  • Set data type
    • Example Set creation and manipulation
    • Frozenset
  • Bool data type
  • Bytes data type
    • bytearray
  • Range data type
  • memoryview

Python is a dynamically typed language; therefore, we do not need to specify the variable’s type while declaring it. Whatever value we assign to the variable based on that data type will be automatically assigned. For example, name = 'Jessa' here Python will store the name variable as a str data type.

No matter what value is stored in a variable (object), a variable can be any type like int, float, str, list, set, tuple, dict, bool, etc.

Also, Solve:

  • Python variables and data type Quiz
  • Basic Python exercise for beginners

There are mainly four types of basic/primitive data types available in Python

  • Numeric: int, float, and complex
  • Sequence: String, list, and tuple
  • Set
  • Dictionary (dict)
Python data types

To check the data type of variable use the built-in function type()  and isinstance().

  • The type() function returns the data type of the variable
  • The isinstance() function checks whether an object belongs to a particular class.

In this article, we will learn the following Python data types in detail.

Data typeDescriptionExample
intTo store integer valuesn = 20
floatTo store decimal valuesn = 20.75
complexTo store complex numbers (real and imaginary part)n = 10+20j
strTo store textual/string dataname = 'Jessa'
boolTo store boolean valuesflag = True
listTo store a sequence of mutable datal = [3, 'a', 2.5]
tupleTo store sequence immutable datat =(2, 'b', 6.4)
dictTo store key: value paird = {1:'J', 2:'E'}
setTo store unorder and unindexed valuess = {1, 3, 5}
frozensetTo store immutable version of the setf_set=frozenset({5,7})
rangeTo generate a sequence of numbernumbers = range(10)
bytesTo store bytes valuesb=bytes([5,10,15,11])
Python Data Types

Str data type

In Python, A string is a sequence of characters enclosed within a single quote or double quote. These characters could be anything like letters, numbers, or special symbols enclosed within double quotation marks. For example, "PYnative" is a string.

The string type in Python is represented using a str class.

To work with text or character data in Python, we use Strings. Once a string is created, we can do many operations on it, such as searching inside it, creating a substring from it, and splitting it.

Example

platform = "PYnative"
print(type(platform))  # <class 'str'>

# display string
print(platform)  # 'PYnative'

# accessing 2nd character of a string
print(platform[1])  # Y

Note: The string is immutable, i.e., it can not be changed once defined. You need to create a copy of it if you want to modify it. This non-changeable behavior is called immutability.

Example

platform = "PYnative"
# Now let's try to change 2nd character of a string.
platform[0] = 'p'
# Gives TypeError: 'str' object does not support item assignment

Int data type

Python uses the int data type to represent whole integer values. For example, we can use the int data type to store the roll number of a student. The Integer type in Python is represented using a int class.

You can store positive and negative integer numbers of any length such as 235, -758, 235689741.

We can create an integer variable using the two ways

  1. Directly assigning an integer value to a variable
  2. Using a int() class.

Example

# store int value
roll_no = 33
# display roll no
print("Roll number is:", roll_no)
# output 33
print(type(roll_no))  
# output class 'int'

# store integer using int() class
id = int(25)
print(id)  # 25
print(type(id))  # class 'int'

You can also store integer values other than base 10 such as

  • Binary (base 2)
  • Octal (base 8)
  • Hexadecimal numbers (base 16)

Example

# decimal int 16 with base 8
# Prefix with zero + letter o
octal_num = 0o20
print(octal_num)  # 16
print(type(octal_num))  # class 'int'

# decimal int 16 with base 16
# Prefix with zero + letter x
hexadecimal_num = 0x10  # decimal equivalent of 21
print(hexadecimal_num)  # 16
print(type(hexadecimal_num))  # class 'int'

# decimal int 16 with base 2
# Prefix with zero + letter b
binary_num = 0b10000  # decimal equivalent of 6
print(binary_num)  # 16
print(type(binary_num))  # class 'int'

Float data type

To represent floating-point values or decimal values, we can use the float data type. For example, if we want to store the salary, we can use the float type.

The float type in Python is represented using a float class.

We can create a float variable using the two ways

  1. Directly assigning a float value to a variable
  2. Using a float() class.

Example

# store a floating-point value
salary = 8000.456
print("Salary is :", salary)  # 8000.456
print(type(salary))  # class 'float'

# store a floating-point value using float() class
num = float(54.75)
print(num)  # 54.75
print(type(num))  # class 'float'

Floating-point values can be represented using the exponential form, also called scientific notation. The benefit of using the exponential form to represent floating-point values is we can represent large values using less memory.

Example

# exponential float
num1 = 1.22e4
print(num1)  # 12200.0
print(type(num1))  # class 'float'

Complex data type

A complex number is a number with a real and an imaginary component represented as a+bj where a and b contain integers or floating-point values.

The complex type is generally used in scientific applications and electrical engineering applications. If we want to declare a complex value, then we can use the a+bj form. See the following example.

Example

x = 9 + 8j  # both value are int type
y = 10 + 4.5j  # one int and one float
z = 11.2 + 1.2j  # both value are float type
print(type(x))  # class 'complex'>

print(x)  # (9+8j)
print(y)  # (10+4.5j)
print(z)  # (11.2+1.2j)

The real part of the complex number is represented using an integer value. The integer value can be in the form of either decimal, float, binary, or hexadecimal. But the imaginary part should be represented using the decimal form only. If we are trying to represent an imaginary part as binary, hex, or octal, we will get an error.

List data type

The Python List is an ordered collection (also known as a sequence ) of elements. List elements can be accessed, iterated, and removed according to the order they inserted at the creation time.

We use the list data type to represent groups of the element as a single entity.  For example: If we want to store all student’s names, we can use list type.

  1. The list can contain data of all data types such as  int, float, string
  2. Duplicates elements are allowed in the list
  3. The list is mutable which means we can modify the value of list elements

We can create a list using the two ways

  1. By enclosing elements in the square brackets [].
  2. Using a list() class.

Example list creation and manipulation

my_list = ["Jessa", "Kelly", 20, 35.75]
# display list
print(my_list)  # ['Jessa', 'Kelly', 20, 35.75]
print(type(my_list))  # class 'list'

# Accessing first element of list
print(my_list[0])  # 'Jessa'

# slicing list elements
print(my_list[1:5])  # ['Kelly', 20, 35.75]

# modify 2nd element of a list
my_list[1] = "Emma"
print(my_list[1])  # 'Emma'

# create list using a list class
my_list2 = list(["Jessa", "Kelly", 20, 35.75])
print(my_list2)  # ['Jessa', 'Kelly', 20, 35.75]

Tuple data type

Tuples are ordered collections of elements that are unchangeable. The tuple is the same as the list, except the tuple is immutable means we can’t modify the tuple once created.

In other words, we can say a tuple is a read-only version of the list.

For example: If you want to store the roll numbers of students that you don’t change, you can use the tuple data type.

Note: Tuple maintains the insertion order and also, allows us to store duplicate elements.

We can create a tuple using the two ways

  1. By enclosing elements in the parenthesis ()
  2. Using a tuple() class.

Example Tuple creation and manipulation

# create a tuple
my_tuple = (11, 24, 56, 88, 78)
print(my_tuple)  # (11, 24, 56, 88, 78)
print(type(my_tuple))  # class 'tuple'

# Accessing 3rd element of a tuple
print(my_tuple[2])  # 56

# slice a tuple
print(my_tuple[2:7])  # (56, 88, 78)

# create a tuple using a tuple() class
my_tuple2 = tuple((10, 20, 30, 40))
print(my_tuple2)  # (10, 20, 30, 40)

Tuple is immutable

A tuple is immutable means once we create a tuple, we can’t modify it

# create a tuple
my_tuple = (11, 24, 56, 88, 78)

# modify 2nd element of tuple
my_tuple[1] = 35
print(my_tuple)
# TypeError: 'tuple' object does not support item assignment

Dict data type

In Python, dictionaries are unordered collections of unique values stored in (Key-Value) pairs. Use a dictionary data type to store data as a key-value pair.

The dictionary type is represented using a dict class. For example, If you want to store the name and roll number of all students, then you can use the dict type.

In a dictionary, duplicate keys are not allowed, but the value can be duplicated. If we try to insert a value with a duplicate key, the old value will be replaced with the new value.

Dictionary has some characteristics which are listed below:

  1. A heterogeneous (i.e., str, list, tuple) elements are allowed for both key and value in a dictionary. But An object can be a key in a dictionary if it is hashable.
  2. The dictionary is mutable which means we can modify its items
  3. Dictionary is unordered so we can’t perform indexing and slicing

We can create a dictionary using the two ways

  1. By enclosing key and values in the curly brackets {}
  2. Using a dict() class.

Example dictionary creation and manipulation

# create a dictionary
my_dict = {1: "Smith", 2: "Emma", 3: "Jessa"}

# display dictionary
print(my_dict)  # {1: 'Smith', 2: 'Emma', 3: 'Jessa'}
print(type(my_dict))  # class 'dict'

# create a dictionary using a dit class
my_dict = dict({1: "Smith", 2: "Emma", 3: "Jessa"})

# display dictionary
print(my_dict)  # {1: 'Smith', 2: 'Emma', 3: 'Jessa'}
print(type(my_dict))  # class 'dict'

# access value using a key name
print(my_dict[1])  # Smith

# change the value of a key
my_dict[1] = "Kelly"
print(my_dict[1])  # Kelly

Set data type

In Python, a set is an unordered collection of data items that are unique. In other words, Python Set is a collection of elements (Or objects) that contains no duplicate elements.

In Python, the Set data type used to represent a group of unique elements as a single entity. For example, If we want to store student ID numbers, we can use the set data type.

The Set data type in Python is represented using a set class.

We can create a Set using the two ways

  1. By enclosing values in the curly brackets {}
  2. Using a set() class.

The set data type has the following characteristics.

  1. It is mutable which means we can change set items
  2. Duplicate elements are not allowed
  3. Heterogeneous (values of all data types) elements are allowed
  4. Insertion order of elements is not preserved, so we can’t perform indexing on a Set

Example Set creation and manipulation

# create a set using curly brackets{,}
my_set = {100, 25.75, "Jessa"}
print(my_set)  # {25.75, 100, 'Jessa'}
print(type(my_set))  # class 'set'

# create a set using set class
my_set = set({100, 25.75, "Jessa"})
print(my_set)  # {25.75, 100, 'Jessa'}
print(type(my_set))  # class 'set'

# add element to set
my_set.add(300)
print(my_set)  # {25.75, 100, 'Jessa', 300}

# remove element from set
my_set.remove(100)
print(my_set)  # {25.75, 'Jessa', 300}

Frozenset

The frozenset data type is used to create the immutable Set.  Once we create a frozenset, then we can’t perform any changes on it.

Use a frozenset() class to create a frozenset.

Example

my_set = {11, 44, 75, 89, 56}
print(type(my_set))  # class 'set'

# creating frozenset
f_set = frozenset(my_set)
print(type(f_set))  # class 'frozenset'

Note: If we try to perform operations like add, remove on frozenset, you will get an error.

Bool data type

In Python, to represent boolean values (True and False) we use the bool data type. Boolean values are used to evaluate the value of the expression. For example, when we compare two values, the expression is evaluated, and Python returns the boolean True or False.

Example

x = 25
y = 20

z = x > y
print(z)  # True
print(type(z))  # class 'bool'

Bytes data type

The bytes data type represents a group of byte numbers just like an array. We use the bytes() constructor to create bytes type, which also returns a bytes object. Bytes are immutable (Cannot be changed).

Use bytes data type if we want to handle binary data like images, videos, and audio files.

Example

a = [9, 14, 17, 11, 78]
b = bytes(a)
print(type(b))  # class 'bytes'
print(b[0])  # 9
print(b[-1])  # 78

In bytes, allowed values are 0 to 256. If we are trying to use any other values, then we will get a ValueError.

Example

a = [999, 314, 17, 11, 78]  # Gives error range must be in 0 to 256
b = bytes(a)
print(type(b))
# ValueError: bytes must be in range(0, 256)

bytearray

The bytearray data type same as the bytes type except bytearray mutable (we can modify its elements). The bytearray() constructor returns a bytearray object.

Example

# create a bytearray
list1 = [9, 17, 11, 78]
b_array = bytearray(list1)
print(b_array)
print(type(b_array))  # class 'bytearray'

# modifying bytearray
b_array[1] = 99
print(b_array[1])  # 99

# iterate bytearray
for i in b_array:
    print(i, end=" ")  # 9 99 11 78

Range data type

In Python, The built-in function  range() used to generate a sequence of numbers from a start number up to the stop number. For example, If we want to represent the roll number from 1 to 20, we can use the range() type. By default, it returns an iterator object that we can iterate using a for loop.

Example

# Generate integer numbers from 10 to 14
numbers = range(10, 15, 1)
print(type(numbers))  # class 'range'

# iterate range using for loop
for i in range(10, 15, 1):
    print(i, end=" ")
# Output 10 11 12 13 14

memoryview

The memoryview is used to create a view of the internal data of an object without copying it. So with the help of memoryview we can see the same data in a different view.

To do this, we need a buffer protocol. The buffer protocol provides a way to access the internal data of an object. This internal data is a memory array or a buffer.

In Python bytes and bytearray are built-in objects that support the buffer protocol. So we can create memoryview on top of those objects.

Syntax to create a memoryview 

memoryview(obj)

Example 1: Creating memoryview of an object

b_array = b'PYnative'
b_array_view = memoryview(b_array)  # creating memory view for bytes objects
print("view object: ", b_array_view)

Output

view object: <memory at 0x0000003396DC6F48>

In the above example, we create memoryview of b_array and print the object in memory view format instead of the original object. If we want an object in its original form, we need to collect the object in a container(like a list or tuple). We can also iterate over each element of the given bytes array.

Example 2: Creating and storing in a container

byte_array = b'PYnative'      # creating bytes array object
byte_array_view = memoryview(byte_array)  # creating memory view for bytes array objects
container = tuple(byte_array_view)   # Storing it in container of iterating
for char in container:
    print(char, end=" ")

Output

80 89 110 97 116 105 118 101

We can also perform indexing and slicing on memoryview same like list and tuple object. So it will return ordinal value for characters at the given index

Example 3: Indexing and slicing on memoryview

byte_array = b'PYnative' # creating bytes array object
byte_array_view = memoryview(byte_array) # creating memory view for bytes array objects

print("byte_array_view[0]:", byte_array_view[0]) # indexing
print('Slicing of b_array_view[6:12] is:', bytes(byte_array_view[6:12])) # Slicing

Output

byte_array_view[0]: 80
Slicing of b_array_view[6:12] is: b've'

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python Basics

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python Object-Oriented Programming
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com