Home Python Data Types
Post
Cancel

Python Data Types

When we talk about data, we can talk about data types, data classes, and data structures.

Data types are fundamental building blocks for storing information. Below, we can see a chart of all of the datatypes in Python.

English nameType nameDescriptionExample
integerintpositive/negative whole numbers13
floating point numberfloatreal number in decimal form3.1415
booleanbooltrue or falseTrue
stringstrtext“Do you like Python?”
listlista collection of objects - mutable & ordered[‘Hi’,’Hello’,’Hola’]
tupletuplea collection of objects - immutable & ordered(‘Tuesday’,3,14,2023)
dictionarydictmapping of key-value pairs{‘name’:’Madison’,’Program’:’Data Science’,’Age’:23}
noneNoneTyperepresents no valueNone

Note that character data, also known as strings, are always wrapped in “quotation marks”. You can use single quotes like ‘this’ or double quotes like “this”. As long as you use two of the same, it doesn’t matter which you use!

We can use the function type() to view the datatype of the stored value in a variable. Let’s explore a few examples of this.

1
2
3
# Datatype 
x = 1 + 1
type(x)
1
## <class 'int'>
1
2
x = 2.0
type(x)
1
## <class 'float'>
1
2
3
# String
string = 'Okanagan'
print(string)
1
## Okanagan
1
type(x)
1
## <class 'float'>

Comparison Operators

We can compare objects (or variables) using comparison operators. The result is a Boolean value. Recall from above that a Boolean gives either a True or False.

First, let’s look at a table of the different comparison operators.

Comparison Operators

OperatorDescription
x == yis x equal to y?
x != yis x not equal to y?
x > yis x greater than y?
x >= yis x greater than or equal to y?
x < yis x less than y?
x <= yis x less than or equal to y?
x is yis x the same object as y?
x and yare x and y both true?
x or yis at least one of x and y true?
not xis x false?

Now, let’s look at a few examples.

1
5 < 7
1
## True
1
2
3
five = 5
seven = 7
five < seven
1
## True
1
5.0 == 5
1
## True
1
5.0 == '5'
1
## False

Lists

Lists are an important tool used in Python. Lists can contain elements of mixed types as well. Let’s look at a few examples.

1
2
3
# List
list1 = []
list1
1
## []
1
2
list2 = [1, 'UBC', 100]
list2
1
## [1, 'UBC', 100]

Now let’s see a few operations we can perform on a list.

1
len(list1)
1
## 0
1
len(list2)
1
## 3
1
2
# Indexing Example - we will talk more about this later on
list2[2]
1
## 100

Note - Python indexing starts at zero, so the first element in the list is 0, the second is 1, and the third is 2, so if we actually wanted the second element, we would have to do this:

1
list2[1]
1
## 'UBC'
1
type(list2)
1
## <class 'list'>
1
type(list2[1])
1
## <class 'str'>

As we mentioned earlier, a main difference between lists and tuples is that lists are mutable. Mutable means that elements in a list can be appended, changed, or deleted.

1
2
3
mixed_list = [1, 'UBC', 5.0, '1']
mixed_list.append('New')
mixed_list
1
## [1, 'UBC', 5.0, '1', 'New']

If we decided that we wanted to replace ‘New’ with 4, we could do so like this:

1
2
mixed_list[4]= 4
mixed_list
1
## [1, 'UBC', 5.0, '1', 4]

If we wanted to remove elements from the list, we could do so like this:

1
2
mixed_list.remove('UBC')
mixed_list
1
## [1, 5.0, '1', 4]

Note that this will only remove the first occurrence, if this happened to be in the list more than once. It would also call an error message if the element doesn’t exist.

If we wanted to remove it based on the index of the list:

1
2
del mixed_list[0]
mixed_list
1
## [5.0, '1', 4]

Dictionaries

A dictionary lists key-value pairs, which could also be thought of as associated values where a key matches to the associated value. Let’s look at a few examples.

1
2
3
# Dictionary - mapping between values
house = {'bedrooms': 3, 'bathrooms': 2, 
         'city': 'Kelowna', 'price': 250000}
1
house['price']
1
## 250000
1
2
course = {'Data Science': ['DATA100', 'DATA200', 'DATA300'],
            'Science': ['SCIENCE100', 'SCIENCE200', 'SCIENCE300']}
1
course['Data Science']
1
## ['DATA100', 'DATA200', 'DATA300']

Loops

Loops are a common tool used in Python to help users iterate through lists, or perform the same operation numerous times without added efforts.

Let’s look at a few examples:

1
2
3
4
5
6
# Loops

for n in [0, 1, 5, 2, -5]:
    # this is inside the loop
    print("The number is", n, "and its squared value is", n**2)
# this is outside the loop
1
2
3
4
5
## The number is 0 and its squared value is 0
## The number is 1 and its squared value is 1
## The number is 5 and its squared value is 25
## The number is 2 and its squared value is 4
## The number is -5 and its squared value is 25
1
2
3
4
## Loop
s = "Python"
for c in s:
    print(c + "!")
1
2
3
4
5
6
## P!
## y!
## t!
## h!
## o!
## n!
1
2
3
# range(10) sets values 0-9, because recall Python starts at 0, not 1
for i in range(10):
    print(i)
1
2
3
4
5
6
7
8
9
10
## 0
## 1
## 2
## 3
## 4
## 5
## 6
## 7
## 8
## 9

This is equivalent to writing:

1
2
for i in range(0,10):
    print(i)
1
2
3
4
5
6
7
8
9
10
## 0
## 1
## 2
## 3
## 4
## 5
## 6
## 7
## 8
## 9

If we wanted it to start at 1 and go to 10 (inclusive), we would write:

1
2
for i in range(1,11):
    print(i)
1
2
3
4
5
6
7
8
9
10
## 1
## 2
## 3
## 4
## 5
## 6
## 7
## 8
## 9
## 10

Other examples:

1
2
3
#(start,end,increments)
for i in range(0,101,10):
    print(i)
1
2
3
4
5
6
7
8
9
10
11
## 0
## 10
## 20
## 30
## 40
## 50
## 60
## 70
## 80
## 90
## 100
1
2
3
4
n = 3
while n > 0:
    print(n)
    n = n - 1
1
2
3
## 3
## 2
## 1
1
print("Smile!")
1
## Smile!

Data Frames

A data frame essentially functions as a series of connected vectors or lists, where each vector or list is a column. In this sense a data frame is also a special kind of list.

In a data frame, all vectors need to be of the same length. And while each vector must hold the same data type, not all vectors need to be of the same data type. Data frames also allow us to apply column names.

Let’s look at an example of creating a dataframe from two lists.

1
2
3
4
5
6
7
8
letter_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
import pandas as pd
df = pd.DataFrame(
    {'Letters': letter_list,
     'Numbers': number_list})

df
1
2
3
4
5
6
7
8
9
10
##   Letters  Numbers
## 0       a        1
## 1       b        2
## 2       c        3
## 3       d        4
## 4       e        5
## 5       f        6
## 6       g        7
## 7       h        8
## 8       i        9

Alternatively, you could write a data frame directly like this:

1
2
3
4
df1 = pd.DataFrame({'x' : [1., 2., 3., 4.],
                   'y' : [4., 3., 2., 1.],
                   'z' : [1, 2, 3, 4]})
df1
1
2
3
4
5
##      x    y  z
## 0  1.0  4.0  1
## 1  2.0  3.0  2
## 2  3.0  2.0  3
## 3  4.0  1.0  4

Data frames are a VERY powerful data type in Python. We will spend most of our remaining time working with data frames because there is so much to learn about.

This post is licensed under CC BY 4.0 by the author.