DEV Community

Cover image for Understanding the Various Data Types in Python
Mohammad Aman
Mohammad Aman

Posted on

Understanding the Various Data Types in Python

In Python, everything you work with has a "type." Think of data types as different categories for your information. When you tell Python that a variable is a certain type, you're telling it what kind of data it holds and what you can do with it. For example, you can do math with numbers, but you can't do math with words.

In Python, Data Types are actually classes, and the variables you create are objects (or instances) of these classes. Since Python is a dynamically typed language, you don't need to specify the data type when you create a variable; Python figures it out at runtime. Let's explore the most common built-in data types.

Numeric Data Types

These are used for numbers. Python has three main types of numbers.

1. Integer (int)

Integers are whole numbers, both positive and negative, without any decimal points.

Example: Mohammad Aman, Sakir, and Najaam are counting their apples.

# Counting apples for friends
aman_apples = 10
sakir_apples = -5 # Sakir owes 5 apples
najaam_apples = 0

print(f"Mohammad Aman has {aman_apples} apples.")
print(f"Type of aman_apples is: {type(aman_apples)}")
Enter fullscreen mode Exit fullscreen mode

2. Float (float)

Floats, or floating-point numbers, are numbers that have a decimal point. They are used for representing numbers that can have fractional parts.

Example: Let's look at the prices of some items.

# Item prices
pen_price = 15.50
book_price = 499.99

print(f"The price of the pen is {pen_price}")
print(f"Type of pen_price is: {type(pen_price)}")
Enter fullscreen mode Exit fullscreen mode

3. Complex (complex)

Complex numbers are used in scientific and engineering calculations. They have a real part and an imaginary part, which is written with a j.

Example: A complex number used in an electrical engineering problem.

# A complex number
electrical_value = 4 + 7j

print(f"The complex value is {electrical_value}")
print(f"Type of electrical_value is: {type(electrical_value)}")
Enter fullscreen mode Exit fullscreen mode

String Data Type (str)

Strings are used to store text. In Python, a string is a sequence of Unicode characters. You can create them by putting characters inside single quotes ('...'), double quotes ("..."), or triple quotes ('''...''' or """...""").

An important thing to know is that Python strings are immutable. This means that once a string is created, it cannot be changed. Any operation that seems to modify a string will actually create a new one.

Example: Let's store the names of our friends.

# Storing names as strings
friend1 = "Mohammad Aman"
friend2 = 'Sakir'
greeting = """Hello Najaam,
How are you today?"""

print(friend1)
print(friend2)
print(greeting)
print(f"The type of friend1 is: {type(friend1)}")
Enter fullscreen mode Exit fullscreen mode

String Operations

You can easily combine strings (concatenation) or get a part of a string (slicing).

# String concatenation and slicing
first_name = "Mohammad"
last_name = "Aman"

# Concatenation
full_name = first_name + " " + last_name
print(full_name) # Output: Mohammad Aman

# Slicing
print(full_name[0:8])  # Output: Mohammad
print(last_name[-2:]) # Output: an
Enter fullscreen mode Exit fullscreen mode

Common String Methods

Python provides many built-in methods to work with strings. Here are a few common ones:

name = "Najaam"
print(name.upper()) # Output: NAJAAM
print(name.lower()) # Output: najaam
print(name.replace("a", "o")) # Output: Nojoom

sentence = "   Hello World   "
print(sentence.strip()) # Output: Hello World
Enter fullscreen mode Exit fullscreen mode

Sequence Data Types

These types allow you to store a collection of items in a specific order.

1. List (list)

A list is a collection of items that is ordered and changeable. This means you can add, remove, or change items after the list has been created. Lists are one of Python's most versatile data types and are written with square brackets [].

To some extent, Python lists are similar to arrays in C. However, a key difference is that a C array can only store items of the same data type, while a Python list can hold items of different data types, like a number, a string, and even another list all in one.

Example: Mohammad Aman creates a list of his favorite fruits and then changes it.

# Mohammad Aman's fruit list
aman_fruits = ["apple", "banana", "mango"]
print(f"Aman's original list: {aman_fruits}")

# He changes his mind and replaces banana with grapes
aman_fruits[1] = "grapes"
print(f"Aman's new list: {aman_fruits}")

# Najaam adds a fruit to the list
aman_fruits.append("orange")
print(f"List after Najaam added a fruit: {aman_fruits}")
print(f"The type of aman_fruits is: {type(aman_fruits)}")
Enter fullscreen mode Exit fullscreen mode

Common List Methods

numbers = [8, 2, 3, 4, 1, 4]

# Add an item to the end
numbers.append(10)
print(numbers) # Output: [8, 2, 3, 4, 1, 4, 10]

# Remove the last item
numbers.pop()
print(numbers) # Output: [8, 2, 3, 4, 1, 4]

# Sort the list
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4, 4, 8]
Enter fullscreen mode Exit fullscreen mode

2. Tuple (tuple)

A tuple is similar to a list, but it is unchangeable (immutable). Once you create a tuple, you cannot alter its contents. Tuples are written with round brackets ().

Example: Sakir stores the coordinates of his home, which should not change.

# Sakir's home coordinates (latitude, longitude)
home_location = (26.7271, 85.9240)

print(f"Sakir's home is at: {home_location}")
print(f"Accessing the first element: {home_location[0]}")

# If you try to change it, Python will give an error!
# home_location[0] = 27.0  # This line would cause an error

print(f"The type of home_location is: {type(home_location)}")
Enter fullscreen mode Exit fullscreen mode

3. Range (range)

The range type represents an immutable sequence of numbers. It's commonly used for looping a specific number of times in for loops. The range() function can take up to three arguments: range(start, stop, step). start is the starting number (defaults to 0), stop is the number to stop before, and step is the increment (defaults to 1).

Example: Print numbers from 0 to 4.

# A range of numbers
for number in range(5):
    print(number, end=" ") # Output: 0 1 2 3 4 

# The type is 'range'
print(f"\nThe type is: {type(range(5))}")
Enter fullscreen mode Exit fullscreen mode

Binary Data Types

These data types are used to handle binary data (data in the form of bytes). This is useful when you need to work with raw data from a file, like an image or audio, or from a network connection.

1. Bytes (bytes)

bytes objects are immutable sequences of single bytes (values from 0 to 255). They are created by prefixing a string with b or using the bytes() function.

Example:

# Creating a bytes object
data_b = b'Hello Najaam'
print(data_b)
# data_b[0] = 72 # This would cause an error because bytes are immutable

data_func = bytes([72, 101, 108, 108, 111]) # Represents 'Hello'
print(data_func) # Output b'hello'

print(f"The type is: {type(data_b)}") 
Enter fullscreen mode Exit fullscreen mode

2. Bytearray (bytearray)

bytearray is similar to bytes, but it is mutable, meaning you can change its contents after it's created.

Example:

# Creating a bytearray object
data = bytearray(b'Hello Sakir')
print(f"Original data: {data}") # Output: bytearray(b'Hello Sakir')

# Modifying the data
data[0] = 74 # ASCII for 'J'
print(f"Modified data: {data}") # Output: bytearray(b'Jello Sakir')
print(f"The type is: {type(data)}") # Output: <class 'bytearray'>
Enter fullscreen mode Exit fullscreen mode

3. Memoryview (memoryview)

memoryview is an advanced type that allows you to access the memory of other binary objects without making a copy, which can be more efficient.

Example:

# Using memoryview with a bytearray
data = bytearray(b'Mohammad Aman')
view = memoryview(data)

# Accessing part of the memory
print(view[9:13].tobytes()) # Accesses the part that says "Aman"
print(f"The type is: {type(view)}") # <class 'memoryview'>
Enter fullscreen mode Exit fullscreen mode

Dictionary Data Type (dict)

A dictionary is an unordered collection of items. Each item is a key-value pair. Dictionaries are changeable and are written with curly braces {}.

Example: Let's store the ages of our friends.

# A dictionary of friends and their ages
friend_ages = {
    "Mohammad Aman": 22,
    "Sakir": 21,
    "Najaam": 23
}

# Accessing Sakir's age
print(f"Sakir's age is: {friend_ages['Sakir']}")

# Adding a new friend
friend_ages["Ali"] = 20
print(f"Updated dictionary: {friend_ages}")
print(f"The type is: {type(friend_ages)}")
Enter fullscreen mode Exit fullscreen mode

Set Data Types

Sets are unordered collections of unique items. This means an item can only appear once in a set.

1. Set (set)

A set is mutable. You can add or remove items from it. Sets are created using curly braces {}.

Example: Najaam has a collection of unique numbers.

# Najaam's set of numbers
najaam_numbers = {1, 2, 3, 4, 4, 5, 2} # Duplicates are automatically removed

print(f"Najaam's unique numbers: {najaam_numbers}") # {1, 2, 3, 4, 5}

# Adding a new number
najaam_numbers.add(6)
print(f"Set after adding a number: {najaam_numbers}") # {1, 2, 3, 4, 5, 6}
print(f"The type is: {type(najaam_numbers)}") # <class 'set'>
Enter fullscreen mode Exit fullscreen mode

2. Frozenset (frozenset)

A frozenset is an immutable version of a set. Once created, you cannot change its contents.

Example:

# A frozenset of allowed permissions
allowed_permissions = frozenset(["read", "write"])

print(f"Allowed permissions: {allowed_permissions}") # frozenset({'read', 'write'})
# allowed_permissions.add("execute") # This line would cause an error
print(f"The type is: {type(allowed_permissions)}") # <class 'frozenset'>
Enter fullscreen mode Exit fullscreen mode

Boolean Data Type (bool)

The boolean type can only have one of two values: True or False. It's used for logical operations.

Example: Is Mohammad Aman old enough to vote? (Assuming voting age is 18)

aman_age = 22
is_old_enough = aman_age >= 18

print(f"Is Mohammad Aman old enough to vote? {is_old_enough}")
print(f"The type is: {type(is_old_enough)}")
Enter fullscreen mode Exit fullscreen mode

None Type (NoneType)

This special data type has only one value: None. It is used to represent the absence of a value or a null value.

Example: A variable is created, but it doesn't have a value yet.

# A variable with no value assigned yet
winner = None

# Later in the program, the winner is decided
if winner is None:
    print("The game has not finished yet.")

winner = "Sakir"
print(f"The winner is {winner}")
print(f"The type of the initial 'winner' was: {type(None)}")
Enter fullscreen mode Exit fullscreen mode

Conclusion

Understanding data types is fundamental to programming in Python. Each type—from simple numbers and strings to complex collections like lists and dictionaries—serves a specific purpose. By choosing the right data type, you can store your data efficiently and use Python's powerful built-in functions to work with it effectively. As you continue your Python journey, a strong grasp of these core data types will be essential for building more complex and powerful applications.

Top comments (0)