Data Types in Python

  • Post category:python
  • Reading time:16 mins read

Introduction

Hi All. In this post, I will tell you about the data types supported in python. Python provides several built-in data types that are commonly used. Here’s an overview of some of the main data types:

Numeric Types:

Python provides three types of numeric types:

  • Integer (int): Integers are whole numbers without a decimal point. They can be positive, negative, or zero. Example: 5, -10, 0.
  • Floating-Point (float): Floating-point numbers are numbers with a decimal point or in exponential form (scientific notation). Example: 3.14, -0.001, 2.0e3 (which is equivalent to 2000.0).
  • Complex (complex): Complex numbers are represented as a + bj, where a and b are real numbers, and j represents the imaginary unit (the square root of -1). Example: 3 + 2j, -1 - 4j.
x = 100
y = 100.00
z = -0.20
p = 4.0e3
q = 1 + 2j

print("Data type of x is: ", type(x))
print("Data type of y is: ", type(y))
print("Data type of z is: ", type(z))
print("Data type of z is: ", type(p))
print("Data type of z is: ", type(q))

# Output
Data type of x is:  <class 'int'>
Data type of y is:  <class 'float'>
Data type of z is:  <class 'float'>
Data type of z is:  <class 'float'>
Data type of z is:  <class 'complex'>

Python also supports operations between different numeric types, automatically converting one type to another as necessary. For instance, if you perform arithmetic operations between an integer and a float, the result will be a float. If you perform operations involving complex numbers, the result will be a complex number if any of the operands are complex.

Sequence Types:

In Python, sequence types are data types that represent sequences of elements. These elements can be of any data type. Here are the main sequence types in Python:

  1. Lists (list):
    • Lists are ordered collections of items.
    • They are mutable, meaning you can change their content after creation.
    • Lists can contain elements of different data types.
    • Example: [1, 2, 'three', 4.0]
  2. Tuples (tuple):
    • Tuples are similar to lists but are immutable, meaning they cannot be modified after creation.
    • They are ordered collections of items.
    • Tuples can contain elements of different data types.
    • Example: (1, 2, 'three', 4.0)
  3. Ranges (range):
    • Ranges represent a sequence of numbers with a range.
    • They are immutable.
    • Range is commonly used for looping a specific number of times in for loops.
    • Example: range(0, 10) represents numbers from 0 to 9.
  4. Strings (str):
    • Strings are sequences of characters.
    • They are immutable like tuples.
    • Example: 'Hello', "Proedu"
list = [1, 2, 'three', 4.0]
tup = (1, 2, 'three', 4.0)
range = (0 , 10)
string = "Hello Proedu"

print("Data type of list is: ", type(list))
print("Data type of tup is: ", type(tup))
print("Data type of range is: ", type(range))
print("Data type of string is: ", type(string))

# Output
Data type of list is:  <class 'list'>
Data type of tup is:  <class 'tuple'>
Data type of range is:  <class 'tuple'>
Data type of string is:  <class 'str'>

Sequence types share some common operations and methods such as indexing, slicing, concatenation, and repetition. However, they also have their unique characteristics. Lists and tuples, for example, can contain elements of different data types, while strings contain only characters. Additionally, lists are mutable, while tuples and strings are immutable.

Mapping Types:

In Python, mapping types are data types that represent collections of key-value pairs. These pairs allow you to store and retrieve data using keys rather than relying on positional indexing. Here are the main mapping types in Python:

Dictionary (dict):

  • Dictionaries are unordered collections of key-value pairs.
  • Keys are unique within a dictionary, and each key is associated with a value.
  • Values can be of any data type, but keys are typically strings or numbers.
  • Example: {'name': 'Proedu', 'age': 5, 'city': 'Delhi'}
map = {'name': 'Proedu', 'age': 5, 'city': 'Delhi'}
print("Data type of map is: ", type(map))

# Output
Data type of map is:  <class 'dict'>

Mapping types allow for efficient lookup operations based on the keys. They are commonly used when you need to associate some data (the value) with a specific identifier (the key). In Python, dictionaries (dict) are the primary mapping type and are widely used in various applications, including data processing, configuration settings, and database operations.

Set Types:

In Python, set types are unordered collections of unique elements. They are designed to efficiently check for membership, eliminate duplicate entries, and perform set operations such as union, intersection, difference, and symmetric difference. Here are the main set types in Python:

  1. Set (set):
    • Sets are mutable collections of unique elements.
    • They are unordered, meaning that the elements are not stored in any particular order.
    • Sets can be modified after creation, allowing for adding or removing elements.
    • Example: {1, 2, 3, 4}
  2. Frozen Set (frozenset):
    • Frozen sets are immutable collections of unique elements.
    • They are similar to sets but cannot be modified after creation.
    • Frozen sets are hashable and can be used as dictionary keys.
    • Example: frozenset({1, 2, 3, 4})
my_set = {1,2,3,4,5}
my_frozen_set = {(1,2,3,4)}
print("Data type of Set is: ", type(my_set))
print("Data type of Frozen Set is: ", type(my_frozen_set))

# Output
Data type of Set is:  <class 'set'>
Data type of Frozen Set is:  <class 'set'>

Sets are commonly used in scenarios where you need to store a collection of unique items or efficiently check for membership. They provide operations for set theory, such as finding intersections, unions, differences, and symmetric differences between sets, making them useful in various algorithms and data processing tasks.

Boolean Type:

In Python, the boolean type (bool) represents truth values, which can be either True or False. Booleans are commonly used for logical operations, conditional expressions, and control flow statements. Here are some key points about the boolean type in Python:

  1. Values: The two possible boolean values in Python are True and False.
  2. Logical Operations: Booleans are often used in logical operations such as and, or, and not.
  3. Comparison Operators: Comparison operators like <, <=, >, >=, ==, and != return boolean values based on the comparison result.
  4. Control Flow: Booleans are integral to control flow statements like if, elif, and else, as well as loop constructs like while and for.
  5. Conversion: Other data types can be converted to boolean values implicitly. Generally, numeric types with a value of zero (0, 0.0, 0j), empty sequences ('', (), [], {}), and None evaluate to False, while non-zero numbers, non-empty sequences, and non-None objects evaluate to True.
  6. Operations: Booleans support operations such as logical AND (and), logical OR (or), logical NOT (not), equality (==), and inequality (!=).
x = True
y = False
print("Data type of Boolean x is: ", type(x))
print("Data type of Boolean y is: ", type(y))

# output
Data type of Boolean x is:  <class 'bool'>
Data type of Boolean y is:  <class 'bool'>
# Using Boolean type with logical operators.
print(x and y)  # Output: False
print(x or y)   # Output: True
print(not x)    # Output: False

# Output
False
True
False
# Boolean type with logical operators.
a = 5
b = 10
print(a < b)
print(a == b)

# Output
True
False
# Boolean in control flow.
if x:
    print("x is True")
else:
    print("x is False")

# Output
x is True

Booleans play a fundamental role in programming as they enable decision-making and control the flow of execution within programs.

Binary Types:

In Python, binary types refer to data types that represent sequences of bytes. Here are the main binary types in Python:

  1. Bytes (bytes):
    • Bytes objects represent immutable sequences of bytes.
    • They can contain any 8-bit value, which includes ASCII characters and binary data.
    • Bytes literals are written with a leading b character, followed by a sequence of bytes literals, e.g., b'hello'.
    • Example: b'hello'
  2. Byte Array (bytearray):
    • Bytearray objects are mutable sequences of bytes.
    • They are similar to bytes objects but can be modified after creation.
    • Bytearray literals are written with a leading bytearray keyword, followed by a sequence of bytes literals or integers representing the byte values.
    • Example: bytearray(b'hello')
  3. Memory View (memoryview):
    • Memoryview objects provide a way to access the internal data of an object that supports buffer protocol (e.g., bytes, bytearray, array.array) without making a copy.
    • They allow efficient sharing and manipulation of memory between different data types.
    • Memoryview objects can be created using the memoryview() function.
    • Example: memoryview(b'hello')
binary_data = b"Hello Proedu"
print("Data type of binary_data is: ",type(binary_data))
print(binary_data[0])
print(binary_data[1])

# Output
Data type of binary_data is:  <class 'bytes'>
72
101

In this example, the data type of binary_data variable is bytes. the values 72 and 101 are the ASCII values of character H and e. Here is another example of encoding and decoding strings to bytes.

# Encoding string to bytes
encoded_bytes = 'Hello Proedu'.encode('utf-8')
print(encoded_bytes)

# Decoding bytes to string
decoded_string = encoded_bytes.decode('utf-8')
print(decoded_string)

# Output
b'Hello Proedu'
Hello Proedu
# Creating a bytearray object and modifying its content.
# Creating a bytearray object
byte_arr = bytearray(b"Hello Proedu")
print(byte_arr)

# Modifying content
byte_arr[0] = 65  # 'A' (ASCII value)
byte_arr.append(33)  # '!' (ASCII value)
print(byte_arr)

# Output
bytearray(b'Hello Proedu')
bytearray(b'Aello Proedu!')
# Creating a memoryview object and accessing its buffer.
# Creating a bytes object
data = b"Hello Proedu"

# Creating a memoryview object
mem_view = memoryview(data)

# Accessing buffer
for byte in mem_view:
    print(byte)

# Output ASCII values of 'H', 'e', 'l', 'l', 'o' ,' ', 'P' , 'r' , 'o' , 'e' , 'd' ,'u'
72
101
108
108
111
32
80
114
111
101
100
117

These binary types are commonly used when dealing with binary data, file I/O operations, network communication, and low-level data manipulation tasks in Python. They provide efficient ways to handle and manipulate raw binary data.