Python Data Types that Programmers Need To Master

Interested in learning the finer points of Python? Learning more about its numerical data types can help solidify many general computer science concepts and certainly help one gain a better grasp on the language itself.
python data types 8

At first glance, computer programming languages such as Python seem much less complex than natural human languages. If you’re reading this, that means that you’re more than capable of learning the fundamentals of Python! Especially since you’ve already survived years of remembering, applying, and practicing the use of countless grammar rules.

Python Data types are very similar to any other language’s syntax structures: they are internal constructs that let you store and manipulate data in an orderly manner so your code can work (and be read) efficiently. However, there are complexities under the hood that aren’t readily apparent. In this article, we’ll cover some important aspects of Python data types to be aware of.

Introduction

Data types in Python are organized in classes. Each class interacts with functions and operators differently, making it highly convenient to recognize each of them ahead of working on your code.

Numeric Types, Sequence Types, Set types, Boolean Types, Dictionary types, (and even Binary Types!) make for all of Python’s Data types, and we’re excited to go through some of the most important ones with you today!

Python Numeric Data Types

Python Numerical Data Types, as the word relates, represent numeric values. Numeric types cover Integers, Floats, and Complex numbers, allowing you to perform all sorts of calculations within Python.

Integers

Integers, also known as ints, are Python’s “whole numbers only” numeric data class implemented as long types of “arbitrary size.” Whenever you type in a number without a decimal point in your code, Python’s interpreter reads it as an integer, no matter if it’s negative, positive, or a plain ol’ zero.

The int keyword also represents a built-in type conversion means via which developers can convert non-integer values to integer values with ease. In the case of decimal values (floating-point values) everything after the 1’s place gets dropped. Let’s see some integer values as they appear in Python:

# create an integer
x = 1
print(type(x), x)

# create a floating point (decimal) value
y = 1.0
print(type(x), x)

# cast to an integer
y = int(y)
print(type(y), y)

# Output
<class 'int'> 1
<class 'int'> 1
<class 'int'> 1

Here we see when the variable y‘s value change from 1.0 to 1 when the int function is used to cast it to an integer value. Also of note; many languages have a defined upper-limit for integer value data types.

In Python, however, the int data type is unbound and restricted only by the word type of the system on which it is used. In the case of 64-bit architectures (most modern computers) that provide an upper limit of 263 – 1 = 9,223,372,036,854,775,807 values. For the curious, a system’s max integer size can be found by the sys.maxsize property. Read here for more detailed info on Python’s integers.

Floats

Floating points, also known as floats, are Python’s decimal numbers and fraction numbers data class. Whenever you type in a number that has a decimal component in your code, Python’s interpreter reads it as a float. Just like integers, it doesn’t matter if its whole number component (numbers to the left of its decimal point) has a negative, positive, or even a 0 value.

Integer values can easily be converted to floats either explicitly via a typecast such as float(1) which results in the value 1.0 or implicitly by adding a float value to an existing integer (even if that value is zero) as follows:

# assign an integer value to x
x = 1
print(type(x))

# The result
<class 'int'>

# Add a decimal value to x
x += 0.0
print(type(x), x)

# the result is cast to a float
<class 'float'> 1.0

Note: Floats can also be typed in with scientific notation by just putting an “e” to the right of its last decimal value as a way to indicate the power of 10.

Complex Numbers Data Type

In a nutshell, complex numbers are composed of a real and an imaginary part. Python comes with some impressive built-in support and modules that can help you tackle mathematical problems within your source code.
You can define complex numbers using a literal form and the complex() function.
The literal form requires you to append the letter j to the imaginary portion of your complex number, as follows:

z = 3 + 2j

Alternatively, you can use the complex() function to define your complex numbers. This function accepts two numeric parameters, with the first value representing the real part and the second parameter representing the imaginary part. Here’s an example:

z = complex(3,2)

Notice that floating-point values can also be used to create complex numbers.

z = 3.14 + 2.71j
type(z)
<class 'complex'>

Python and its Cmath module allow you to represent numbers in rectangular and polar coordinates, plot vectors, and even operate complex numbers in advanced arithmetic expressions. In our Python numbers piece, we’ve discussed Python complex numbers (and their most popular functions) in greater detail. Feel free to check it out!

Remember: you can always apply Arithmetic Operators to all of Python’s Numeric Types, allowing you to add, subtract, divide, multiply and exponentiate (and more) depending on your coding needs.

However, applying the same operators to other Data types such as Sequence Types and Binary Types will give you outputs that differ from a strictly mathematical one.

Sequence Data Types

Python Sequence Data Types, as the word relates, allow you to store multiple values in an organized and efficient fashion. The primary Sequence Types cover Strings, Lists, Tuples, and Range (also called Range objects), making Data handling super easy and convenient.

Strings

Strings represent textual data as immutable sequences of characters. By putting together a collection of characters within single, double (or even triple quotes), you can make an array of literal values, even if there are numbers inside the quotes!

In Python, strings are marked with the str syntax. You can think of strings as a sequence of values whose elements are characters. For instance, let’s say we assign a sequence of characters (that are in between quotes) to a variable:

a = "hey dude"
print(type(a))

If we call Python to print the type function of our variable “a”, the terminal will show:

<class 'str'>

Notice that Python also interprets each character within a string as a string in itself! If a string is a sequence of values, we can ask Python to specify each character based on its position within a string.

We can do this by typing the variable to which our string is assigned and adding two closed brackets [ ] with a number that relates to the position of each character within our string. We know this may sound like a mouthful, but the next couple of examples can show you what this all means: First, we assigned "hey dude" value to our variable, then called this closed bracket operator.

a = "hey dude" 
print(a[0])

Once you run the program, the terminal shows:

h

Python will then return the character stored in position 0 of our string. This process is known as indexing a string (more on that later!). Let’s try doing the same thing again progressively to see if Python can also give us the rest of the characters within our strings:

a = "hey dude" 
print(a[0])
print(a[1])
print(a[2])
print(a[3])
print(a[4])
print(a[5])
print(a[6])
print(a[7])

Once you run the program, the terminal shows:

h
e
y

d
u
d
e

Python confirms that our string “Hey dude” is a sequence of characters that looks like ['h', 'e', 'y', '', 'd', 'u', 'd', 'e']. Let’s also verify that each of the characters in our string is a string in itself by calling the type function on any of its characters:

a = "hey dude" 
print(type(a[3]))

Once you run the program, the terminal shows:

<class 'str'>

The return value tells us that the third character in our string (the space between the letter y and d in hey dude) is of class string. But what if we ask Python to give us the character next to that last "e", also known as a[8], in our string?

a = "hey dude" 
print(type(a[8]))

Once you run the program, the terminal shows:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: string index out of range

Python returns an error value that looks pretty cryptic. But the important thing is to notice the phrase that comes after IndexError. It spells string index out of range. This error teaches us that a string can only be as long as the number of characters that compose it. Thankfully, there’s a handy function that calculates the length of a string — the python len() function. We can call this function the same way we apply the type function:

a = "hey dude" 
print(len(a))

Once you run the program, the terminal shows:

8

Python returns an 8, effectively telling us that there are a total of 8 indexes within our string. The index ranged from 0 to 7, meaning that a[8] was out of our string’s range. Likewise (and by this logic), if we order Python to print the a[-1] index we see the following output:

a="hey dude"
print(a[-1])

Our terminal will show the same value as if we were printing the last index of our variable:

e

This means that Python positioned itself on the first index [0], and went back one step back [-1] on our string, printing the last "e" of "hey dude". As you can imagine, this opens up a world of possibilities and interactions between data types and operators. We’ll go deeper on arithmetic and comparison operators and how to make the most out of each data type at a later time.

The List Data Type

A list is a value that contains multiple values in an ordered sequence. The values contained within a list are called “items”, while the “list value” is the list itself.
It’s important to distinguish this right from the get-go since lists can be stored in variables or passed to a function. This unique behavior turns lists into a fantastic data handling and organization tool. Here’s a quick example:

test = ['keyboard', 'cpu', 'monitor', 'mouse']

We assigned the test variable the list value. The list contains four items: keyboard, CPU, monitor, mouse. Python also allows you to access items in a list, even if the list has been assigned to a variable. Let’s name our variable test.

For instance, if we typed test[0] into our source code, we’d get the first item in our list (keyboard). The integer inside the brackets is what’s called an index. Each item in a list has its own index and can be evaluated in many ways. Our list’s items and corresponding index look something like this:

data types list 1
Our “test” list example with its items and corresponding indexes.

We can also evaluate test[3] like this:

test = ['keyboard', 'cpu', 'monitor', 'mouse']
print(test[3])
mouse

You can also edit an item’s value by assigning values to its index. I’ll call on our original list and then edit it. We’ll change the monitor item to mousepad as follows:

test = ['keyboard', 'cpu', 'monitor', 'mouse']
test[2] = "mousepad"

This updated version of our test list now features mousepad instead of monitor.

test = ['keyboard', 'cpu', 'monitor', 'mouse']
test[2] = "mousepad"
print(test)
['keyboard', 'cpu', 'mousepad', 'mouse']

Quick disclaimer: the correct way to modify list values is through the delete command and append method., which we’ll explore in a future article. The statements we previously used allows our variable to hold a new list value that includes mousepad as a new item.

This disclaimer will make sense once you’ve started using loops through a list in Python and learn how to pass list references. For now, treat this as a not-too-important footnote as you take your first steps into learning Python.

Lists can also be concatenated, replicated, and much more. Some of its most basic yet powerful applications are combining Loops with Lists, finding specific values with the index() method, and sorting them with the sort() method.

We’ll dive deeper into some of these powerful applications at a later time to keep things brief. Still, as you can already imagine, lists are incredibly powerful data handling tools with nearly endless possibilities.

Tuple Data Type

A tuple shares some similarities with the list data type but features two critical differences:

  1. Tuples are expressed with parentheses instead of square brackets.
  2. Unlike Lists, Tuples are immutable. Its data cannot be modified, appended, or removed.

Here’s an example of a tuple:

tuple_example = ('7', 'seventy-seven', 'four', '5', 'eight', '9')

Tuples are traditionally used to let others know that you don’t want that sequence of values to ever change. They see little use outside of this particular scenario but can be a handy resource when you’re collaborating with others.

Note: if you want to have a tuple with a single item, you need to add a comma after the value inside the parentheses.

The Range Data Type

The range data type is one of Python’s most popular sequence data types. The range function can only be used within a loop to generate a sequence of numbers.

This function only accepts integers as values, so floating points cannot be part of a range function.

Range accepts up to three arguments. Each argument serves a specific purpose:

data types range 1
Range function and its parameters.
  1. Start: The function’s first argument (0 in this case) specifies the starting point in your series of numbers. If you don’t specify a starting point, Python will assume it’s 0.
  2. Stop: the function’s second argument (5 in this case). It specifies where the series stops.
  3. Step: the function’s third argument (1 in this case). This value represents the difference between one number and the next (if you don’t specify a step argument, Python will assume it’s 1).

Note: you can use positive numbers in the “step” portion of the function to increment a count or negative numbers to decrement it.

You can also call on the Range function using two arguments. Here’s an example:

for i in range (1,7):
    print(i)

1
2
3
4
5
6

In this case, the number “1” serves as the starting point, while integer “7” represents the series’ stopping point. Notice that the series stops at 6 because the range function includes every number except for its “stop” value.

Last but not least, you can use the Range function using only one argument. Here’s an example:

for a in range (5):
    print(a)

0
1
2
3
4

The integer 5 serves as the function’s stopping point. Python will automatically assume that the function’s starting point is “0” and its step value is “1”.

Binary Data Types in Python

All our files, whether they’re videos, images, or text, are essentially zeroes and ones to our computers, which organize all of this data into bits.

From a more granular perspective, there are 8 bits in a byte. Each byte can store a sequence of values ranging from 0-255 that once initialized becomes immutable.

Bytes have a specific syntax and function in Python, as seen below.

Here’s how to use bytes(<size>):

>>> c = bytes(8)
>>> c
b'\x00\x00\x00\x00\x00\x00\x00\x00
>>>len(c)
8

The bytes in the embed above are empty, yet we cannot modify their value using this function. To do that, we need to turn to the bytearray data type.

bytearray Data Type

The bytearray datatype turns bytes into a mutable sequence of integers ranging from 0 to 255. As seen below, you can append, overwrite, and remove elements to change the bytearray object.

>>> arr = bytearray((0, 1, 2, 3))
>>> arr[1]
1

>>> # The bytearray repr:
>>> arr
bytearray(b'\x00\x01\x02\x03')

>>> # Bytearrays are mutable:
>>> arr[1] = 23
>>> arr
bytearray(b'\x00\x17\x02\x03')

>>> arr[1]
23

>>> # Bytearrays can grow and shrink in size:
>>> del arr[1]
>>> arr
bytearray(b'\x00\x02\x03')

>>> arr.appendr(42)
>>> arr
bytearray(b'\x00\x02\x03*')

Note: Python shows the data inside each bit in hexadecimal values. In any case, if this seems a little bit cryptic, we recommend checking our piece on bytearrays for some extra clarity

Python Memoryview Function

Lastly, there is the memoryview function, which allows you to safely access an object’s internal buffers. Keep in mind that memoryview only read-only access to the object’s data; it can neither copy it nor modify it in any way.

This function is mostly used to peer into a large amount of data without copying its content, which could use up significant resources. The function’s syntax is as follows:

memoryview(obj)

Binary data in Python is also used for Encoding, a topic that deserves a more nuanced explanation later. Through character encoding, computers can interpret, represent and send human-readable characters because they assign values to bytes and represent said characters.

Closing Words

Code, just like human languages, uses different syntax structures and syntax rules to represent information. The key is to organize words in structures (like sentences and paragraphs) to convey ideas that everyone can read and understand.

In this article, we’ve taken a bird’s-eye look at some of the most important Python data types, covering some of the most basic functions and operators they have to offer. We highly recommend you check out each of our dedicated pieces to better understand how you can implement these wonderful resources into your own applications!

Dan Aveledo
Bachelor of Business Administration. Specialized in SEO, web development, and digital marketing during the last decade. Currently discovering the endless possibilities that coding offers. In my spare time, you'll find me lifting weights and creating tools that make my life easier.