Data Types in Python

Python is a versatile and powerful programming language that is widely used in various fields, from web development to data science. One of the fundamental concepts in Python, as in any programming language, is data types. Understanding Data types in Python is essential for writing effective and error-free code. In this blog post, we will explore the different data types available in Python, with examples to illustrate each type.

What are Data Types? Data Types in Python

Data types define the type of data that a variable can hold. They determine what kind of operations can be performed on the data and how the data is stored. Python has several built-in data types, and they can be categorized into different groups, such as numeric, sequence, mapping, set, and others.

How Many Data Types In Python:

Python has several built-in data types, each serving different purposes. Here’s a brief overview:

  1. Numeric Types:
    • int: Represents integers, e.g., 1, -2, 3.
    • float: Represents floating-point numbers, e.g., 3.14, -2.0.
    • complex: Represents complex numbers, e.g., 1+2j.
  2. Sequence Types:
    • str: Represents strings, e.g., “hello”.
    • list: Represents ordered collections, e.g., [1, 2, 3].
    • tuple: Represents ordered, immutable collections, e.g., (1, 2, 3).
  3. Mapping Type:
    • dict: Represents key-value pairs, e.g., {“name”: “Alice”, “age”: 25}.
  4. Set Types:
    • set: Represents unordered collections of unique elements, e.g., {1, 2, 3}.
    • frozenset: Represents immutable sets.
  5. Boolean Type:
    • bool: Represents Boolean values, True or False.
  6. Binary Types:
    • bytes: Represents immutable sequences of bytes.
    • bytearray: Represents mutable sequences of bytes.
    • memoryview: Represents memory views of byte data.

These data types provide the foundation for handling various types of data in Python.

Data Types in Python With Examples:

Numeric Data Types in Python

Numeric data types are used to store numeric values. Python supports three different numeric types:

Integer (int)

Integers are whole numbers without a decimal point. They can be positive or negative.

age = 25
print(type(age)) # Output: <class 'int'>
Example:
a = 10
b = -5
print(a)                # Output: 10
print(b)               # Output: -5
print(type(a))     # Output: <class ‘int’>
print(type(b))    # Output: <class ‘int’>

Float (float)

Floats are numbers that contain a decimal point.

price = 19.99
print(type(price)) # Output: <class 'float'>
Example:
c = 3.14
d = -0.001
print(c)               # Output: 3.14
print(d)              # Output: -0.001
print(type(c))     # Output: <class ‘float’>
print(type(d))    # Output: <class ‘float’>

Complex (complex)

Complex numbers have a real and an imaginary part, represented as a + bj.

complex_num = 1 + 2j
print(type(complex_num)) # Output: <class 'complex'>
Example:
e = 2 + 3j
f = -1 – 5j
print(e)              # Output: (2+3j)
print(f)              # Output: (-1-5j)
print(type(e))   # Output: <class ‘complex’>
print(type(f))   # Output: <class ‘complex’>

Sequence Data Types in Python

Sequence data types are used to store collections of items. Python supports several sequence types:

String (str)

Strings are sequences of characters enclosed in quotes.

greeting = "Hello, World!"
print(type(greeting)) # Output: <class 'str'>
Example:
greeting = “Hello, World!”
print(greeting)                 # Output: Hello, World!
print(type(greeting))       # Output: <class ‘str’>

List (list)

Lists are mutable sequences of items. You can change their content without changing their identity.

fruits = ["apple", "banana", "cherry"]
print(type(fruits)) # Output: <class 'list'>
Example:
fruits = [“apple”, “banana”, “cherry”]
print(fruits)                 # Output: [‘apple’, ‘banana’, ‘cherry’]
print(type(fruits))       # Output: <class ‘list’>

Tuple (tuple)

Tuples are immutable sequences of items. Once created, their content cannot be changed.

coordinates = (10, 20)
print(type(coordinates)) # Output: <class 'tuple'>
Example:
colors = (“red”, “green”, “blue”)
print(colors)                # Output: (‘red’, ‘green’, ‘blue’)
print(type(colors))      # Output: <class ‘tuple’>

Range (range)

Ranges represent an immutable sequence of numbers, commonly used for looping a specific number of times in for loops.

numbers = range(5)
print(type(numbers)) # Output: <class 'range'>
Example:
for i in range(5):
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4

Mapping Data Types in Python

Mapping data types store data as key-value pairs. Python has one built-in mapping type:

Dictionary (dict)

Dictionaries are mutable collections of key-value pairs.

person = {"name": "Ram", "age": 25}
print(type(person)) # Output: <class 'dict'>
Example:

person = {
“name”: “Ram”,
“age”: 30,
“profession”: “Engineer”
}

print(person[“name”])            # Output: Ram
print(person[“age”])              # Output: 30
print(person[“profession”])   # Output: Engineer


Set Data Types in Python

Set data types are used to store collections of unique items:

Set (set)

Sets are unordered collections of unique items.

unique_numbers = {1, 2, 3, 4, 5}
print(type(unique_numbers)) # Output: <class 'set'>
Example:

fruits = {“apple”, “banana”, “cherry”}
print(fruits)                         # Output: {‘apple’, ‘banana’, ‘cherry’}

# Adding an element to the set

fruits.add(“orange”)
print(fruits)                        # Output: {‘apple’, ‘banana’, ‘cherry’, ‘orange’}

# Removing an element from the set

fruits.remove(“banana”)
print(fruits)                        # Output: {‘apple’, ‘cherry’, ‘orange’}


Frozen Set (frozenset)

Frozen sets are immutable versions of sets.

immutable_set = frozenset([1, 2, 3, 4, 5])
print(type(immutable_set)) # Output: <class 'frozenset'>
Example:

# Creating a frozenset

fruits = frozenset([“apple”, “banana”, “cherry”])
print(fruits)                                      # Output: frozenset({‘apple’, ‘banana’, ‘cherry’})

# Trying to add an element to a frozenset (will raise an error)
# fruits.add(“orange”) # AttributeError: ‘frozenset’ object has no attribute ‘add’

# Checking membership
print(“apple” in fruits)                      # Output: True
print(“orange” in fruits)                   # Output: False


Boolean Data Type in Python

The boolean data type represents one of two values: True or False.

is_active = True
print(type(is_active)) # Output: <class 'bool'>
Example:

# Defining boolean variables
is_raining = True
is_sunny = False

print(is_raining)        # Output: True
print(is_sunny)         # Output: False

# Boolean expressions

a = 5
b = 10
print(a > b)          # Output: False
print(a < b)         # Output: True
print(a == b)      # Output: False


None Type

The None type represents the absence of a value or a null value.

nothing = None
print(type(nothing)) # Output: <class 'NoneType'>
Read:

Summary

Understanding data types is crucial for writing effective Python code. Each data type serves a specific purpose and has its own set of operations. Here’s a quick summary of the data types we covered:

  • Numeric: int, float, complex
  • Sequence: str, list, tuple, range
  • Mapping: dict
  • Set: set, frozenset
  • Boolean: bool
  • None Type: NoneType

By mastering these data types, you can manipulate and store data efficiently in your Python programs. Keep practicing and experimenting with these data types to deepen your understanding.

Thank you for reading our blog post on data types in Python. We hope you found it helpful and informative. If you have any questions or feedback, please leave a comment below. Happy coding!

 

Leave a Comment