Home
About Us Privacy Policy
 

DATA TYPES IN PYTHON

ADVERTISEMENT

Beginner Data Types



What are Data Types, and what purpose do they serve?

In programming, data types represent the classification of stored information and the operations performed using them. To understand data types in programming, we must first understand the concept of types in general. Therefore, before delving into the programming, I would like to explain types using more understandable, real-world examples.

Let's talk about vehicles, shall we? We all love them. They make our life easier, allows us to go from place to place quickly, and are mostly reliable. However, when we generalize the term 'vehicles,' the interpretation would differ from individual to individual. Some might think of a scooter, a motorbike, a bicycle, or a car as a vehicle. It will entirely depend on the preference of an individual.

Now, let's assume you are fascinated by cars, own one, and want to get some performance tuning done. Your queries could be "car tuning around me," "best car tuning in my city," "car performance tuning," etc. Doing so will make your task much more manageable because your target is car-relevant search results. You won't have to skip irrelevant searches targeting different vehicles you are not interested in, saving time and energy.

In programming, data types act similarly, categorizing information that is efficiently processed. As covered in variables, there can be different types of information such as Name, Age, Phone number, etc. However, they all being relevant information, but they need to be processed using various methods since they don't share common characteristics with other data types.

Let's take age as an example. If somebody were to ask you how old you will be five years from now, you could comfortably answer it by adding five to your current age. If someone asks, what your name will be five years from now, you would be confused as you won't understand the intention behind the question. As a result, you won't answer it and eventually have to confirm the question, resulting in awkward facial expressions. While developing applications, you cannot afford to spend time due to vagueness. Hence, to avoid ambiguity while processing data, data types are required, as they provide attribute transparency, allow efficient data processing, and provide the required information.

Data types avoid ambiguity allowing efficient data processing and providing required information.


ADVERTISEMENT

What are the different data types provided in Python?

In the Python programming language, there are seven pre-defined in-built data types, as shown below.

Numeric Data Type:
  • int, e.g., 8, 17
  • float, e.g., 3.14, 19776.23
  • complex, e.g., 7+1j

String Data Type:
  • str, e.g., "Hello, Programmer!"

Sequential Data Types:
  • list, e.g., [1, 29, 44]
  • tuple, e.g., (31, 821, 3)
  • range, e.g., range(1, 8)

Dictionary:
  • dict, e.g., {"lang": "Python"}

Set Type:
  • set, e.g., set([31, 3212, 81, 96])

Boolean:
  • bool, e.g., False, True

Binary Data Types:
  • bytes, e.g., b'John Doe', bytes("John Doe".encode("UTF-8"))
  • bytearray, e.g., bytearray("John Doe".encode("UTF-8"))
  • memoryview, e.g., memoryview(b"John Doe".encode("UTF-8"))


When to use what data types?

During the development cycle of any program, the programmer would use many variables to store diverse information that is different in characteristics but associated with each other. For example, details about an individual's bank account would have their name, mobile number, residence address, bank balance, etc. Hence, to represent real-world information in a computer program, it is imperative to understand the exact nature of data and what operations are suitable for them. Fortunately, Python, a high-level language, provides a high level of abstraction, as we will learn shortly.

Let us take bank details as an example and understand the various information it comprises. Most of us are aware of the details required, but I'll reiterate. A personal bank account must belong to some entity, and that entity would have the following:

  • your full name
  • residential address
  • date of birth
  • marital status
  • gender
  • bank balance
  • has overdraft protection
  • credit due
  • credit card details such as number, CVV, expiry date

Let's do a little exercise, guess the type of data each attribute belongs to; after that, click to reveal to check.

If your answer is at least 80% correct, pat yourself on the back.

Now that you have developed a thorough understanding of data types, let's represent the above in Python.

first_name = "James"
last_name = "Bond"
middle_name = None
residential_address = "007, Blakely Street, London, United Kingdom A7 7JB"
date_of_birth = "Jan/01/1980"
marital_status = "Single"
gender = "Male"
bank_balance = 7000000.00
currency = "GBP"
has_overdraft_protection = True
credit_due = 0.00
credit_card_details = {
    "number": 1234_5678_1234_5678,
    "cvv": 007,
    "expiry": "07/25"
}

Python allows using _ (underscore) to separate digits in numeric data type to improve readability.

As you may have noted, our Python code representing a piece of real-world information is almost on par with the way actual bank details are stored. This example expresses the power of Python's abstract data types that enables software developers to focus on solving real-world problems effortlessly, quickly, efficiently with minimal errors.


ADVERTISEMENT

None Type

The attribute "middle name" is not a textual data type in the above example due to the entity not having a middle name. In other lower-level programming languages, you would assign it a value of "blank" like this "" and not having any information within the quotes. Doing so decreases the readability of the program and increases ambiguity. But how?. It raises a few questions: Are the details corrupted in the database, does the entity not have a middle name, or will it be assigned later? Since readability is one of the cornerstones of the Python programming language, it provides a particular data type, i.e., NoneType, expressed as None, to handle such situations explicitly.

middle_name = None


Bytes Data Type

Python allows for directly embedding byte data in source files. To append byte data, prepend a "b" before the string. Here is an example:

my_string = "abcdefghijklmnop0123456789"
print(my_string[0])   # a

my_byte_string = b"abcdefghijklmnop0123456789"
print(my_byte_string [0])   # 97

a
97


The bytes() method

You can also create a byte data type from string using the bytes() method. Below is an example:

my_string = "Hello, World is the first thing a future developer prints on the screen."
my_string_encoded = my_string.encode("UTF-8")
my_string_in_bytes = bytes(my_string_encoded)
print(my_string_in_bytes)

b'Hello, World is the first thing a future developer prints on the screen.'

We will cover bytes() in detail in Typecasting.


Binary Data Type

Sometimes, it is easier to write binary values for faster development directly, especially when manipulating values on the bit level. Python allows for directly embedding binary data in source files. To append binary data, prepend a "0b" before the value. Here the value can only be 0 or 1. Below is an example:

nine_in_binary = 0b1001
one_in_binary = 0b00_01
print(nine_in_binary - one_in_binary)

8


Getting the type of variable

During the software development cycle, you might need to check the type of the variable. Python provides an in-built method to achieve that:
the type() method.

my_name = "James Bond"
print(type(my_name))

<class 'str'>


ADVERTISEMENT

Asserting the type of the variable

Sometimes, we might need to check the type of the variable before performing operations with it. To achieve that, Python provides an in-built method isinstance().

The below example uses a yet-uncovered feature if-else and str; ignore it briefly and focus on the isinstance() method.

ambiguous_var = "James Bond"
if isinstance(ambiguous_var , str):
    print(f"ambiguous_var is {type(ambiguous_var)}, its value {ambiguous_var}")
else:
    print(f"ambiguous_var is not str type")

ambiguous_var is <class 'str'>, its value James Bond

As demonstrated above, it is better to check the type of value a variable contains before processing any data, thereby following the principles of the Python programming language, explicit is better than implicit.

Some of the in-built types are:

  • str
  • int
  • float
  • complex
  • list
  • tuple
  • None

The below example contains yet-untouched concepts such as Lists, Tuples, Class.

str_type = "string"              # str
int_type = 8                     # int
float_type = 4.4                 # float
complex_type = 8j                # complex
list_type = [1, 2, 3, 4]         # list
tuple_type = (1, 2, 3, 4)        # tuple
class ClassType:                
    pass
class_type = ClassType()         # class
none_type = None                 # None

print(isinstance(str_type, str))
print(isinstance(int_type , int))
print(isinstance(float_type , float))
print(isinstance(complex_type , complex))
print(isinstance(list_type , list))
print(isinstance(tuple_type , tuple))
print(isinstance(class_type , ClassType))
print(isinstance(none_type, None))

True
True
True
True
True
True
True
True


Iterable Types

Iterable types in Python are data types that can be iterated upon. The data types such as:

  • Lists
  • Tuples
  • String
  • Iterator Object
are classified as Iterable Types. We will discuss them later separately.


Conclusion

In this chapter, we learned about the rationality behind data types and their purpose in application development. We also learned about the different data types provided by Python, choosing the appropriate data types, using underscores(_) to improve the readability of numerical data types, and fetching and asserting the type of the variable using in-built methods provided by Python.


ADVERTISEMENT



All product names, logos, and brands are property of their respective owners.