20
Data Types in Python
Have you ever stored some piece of information in the computer and wondered how the computer represents these information? Well, for you it might seems like a bunch of text or a bunch of numbers. But the computer sees this information differently. This is the reason why the computer can perform more rigorous and complex computations than all the human efforts combined. This is made possible through the concept of ”Data Types”.
Because the computer knows how to represent this data in the memory, that is why it can manipulate the data so well. A human will out of the box tell you that 1 + 1 = 2
, but a computer can’t directly give you the answer without first checking how the expression is represented in the memory. This is where the concept of data types comes to play.
- Have the latest version of Python installed on your computer
A datatype is an attribute of a data which tells the computer how a data is to be used. The data type of a variable defines the meaning of a data, the operations that can be performed on that data, and how the data is stored in the memory.
Python provides for us a rich set of built-in data types that can be used in programs without creating them from scratch. However, you can also write your own data type in Python to add some of the custom features not included in the ones provided by Python.
This article discuses some of the basic data types in Python.
The three numeric data types python provides are integers, float, and complex.
An integer is a whole number, it can be positive or negative. In Python, there is no limit to how long an integer can be. It can be as long as you want it, except that it is constrained by the memory of your computer. Numbers like -1, 0, 3, 99999999999999999 are a perfect fit for integers.
A float in Python is any number that has a decimal point. It designates a floating-point number. Floats can be positive or negative numbers. It also doesn't have a limit to how long it can be just like integers. Numbers like -0.1, 0.0, 1.5, 12345.678890000000. Note that floating-point numbers can contain only 1 decimal point. Using more than one decimal point for a floating number will throw a SyntaxError
.
You could also append the letter e
or E
followed by an integer to represent a scientific notation.
Python represents floating-point numbers with 64-bit double-precision values in almost all platforms. This implies that the maximum value a floating-point number can be is approximately 1.8 ⨉ 10308. Any number greater than this will be indicated with the string inf
implying Infinity.
Similarly, the minimum value a floating number can be is 5.0 ⨉ 10-324. Any number smaller than this will be effectively zero.
A complex number is a number containing a real and imaginary part. A typical complex number looks like a+bj
, where a is the real part and b is the imaginary part. You can create a complex number using the complex()
function. This function takes in two arguments. The first is the real part and the second is the imaginary part.
You can alternatively create a complex number by just appending a j
to the end of the imaginary part. This will set the real part to zero and the imaginary part to whatever value was specified.
Complex numbers also provide two attributes that you can use to get the real and imaginary parts of the complex number. If the variable a
is a complex number, then you can access the real and imaginary parts of a
using a.real
and a.imag
.
Boolean values in Python are used to represent truth values. They consist of constants True
and False
. Boolean values can also behave like integers when used in numeric concepts, where True
evaluates to 1 and False
evaluates to 0.
Python provides for us the in-built function bool()
which can be used to convert any value to a Boolean. The bool()
function takes in an input and returns the boolean values True
or False
depending on the input. By default, the output is True
. It is False
if it falls under any of the following:
- Every constant returns
False
, includingNone
andFalse
- The zero value of any numeric data type returns
False
. E.g0
,0.0
,0j
,Decimal(0)
,Fraction(0, 1)
- Empty sequence returns
False
. E.g''
,()
,[]
,{}
,set()
,range(0)
Boolean values are handy when using conditionals and loops such as if … else
, while
, for
in your programs. The truth value of a boolean expression is what determines whether a particular section of code is executed on not as in loops and conditionals.
In Python, a sequence is an ordered collection of data. This data can be similar or different data types. Some of the sequence types in Python include:
- Strings
- List
- Tuples
A string is a sequence of letters, space, punctuation marks, or even numbers. It is an immutable sequence of code points. Python handles any form of textual data using the str
object. Unlike integers, strings are represented differently in the computer’s memory that is why they cannot be used to perform arithmetic operations.
Strings are represented using either single, double, or triple quotes. Python does not have a type for a single character. A single character is a string with a length of 1.
- Creating Strings
# Creating a string with a single quote
single = 'Hello, World!'
print(single)
# Creating a string with double-quote
double = "Hi, i'm Prince"
print(double)
# Creating a string with a triple quote
triple = """
The conversation went as follows:
Me: Hello
Her: Hey
"""
print(triple)
## Output
# Hello, World!
# Hi, i'm Prince
# The conversation went as follows:
# Me: Hello
# Her: Hey
Python represents strings in either single, double, or triple quotes. The starting quote of a string must be the same as the end quote. A string cannot start with a single quote and end with a double quote. This will throw a SyntaxError
. But a single quote string can contain a double quote string inside, and a double quote string can contain a single quote string inside, like the double
variable in the above snippet.
The triple quote string can span multiple lines. Making it possible to write multi-line strings.
- Accessing the elements of a string
In Python, the elements of a string can be accessed using Indexing
. Indexing allows us to use the index of a string to access it. The first index of a string is 0, the second is 1, and so on. The last index of a string is -1, the second to last is -2, and so on.
# Accessing elements of a string
message = "Hello, World!"
print(message[0]) # The first element of the string
print(message[-1]) # The last element of a string
print(message[13]) # IndexError
## output
# H
# !
# IndexError: string index out of range
When accessing string elements using indexing, ensure that the index is within the range of the string. If the index entered is out of range, Python will throw an IndexError
.
A list is a mutable sequence of data that is used to store data. List in Python is similar to arrays in other languages, but they don’t have to be of the same type. A list can be created either by using a pair of square brackets containing iterables
or using the type constructor list()
that takes in an iterable
.
An
iterable
is any sequence or container that can be iterated upon (loop through).
# List
# create an empty list
a = []
b = list()
print(a)
print(b)
# list with values of different types
mixed = [1, 2, 3, 4, True, False, 'a', 'b', 'c', 'd']
print(mixed)
# using the list() function
list_function = list(mixed) # create a copy of the `mixed` list
print(list_function)
iterable = list(range(10))
print(iterable)
tuple_inside_function = list((1, 2, 3))
print(tuple_inside_function)
## output
# []
# []
# [1, 2, 3, 4, True, False, 'a', 'b', 'c', 'd']
# [1, 2, 3, 4, True, False, 'a', 'b', 'c', 'd']
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [1, 2, 3]
A list can either be a single-dimensional or multidimensional list. A single-dimensional list contains a sequence of data. A multidimensional list contains iterable
such as a list. A list containing lists is an example of a multidimensional list.
# List dimensions
# single dimensional
alphanumeric = ['a', 'b', 'c', 'z', 0, 1, 2, 9]
print(alphanumeric)
print(alphanumeric[5])
# multidimensional
alphanumeric = [['a', 'b', 'c', 'd'], [0, 1, 2, 9]]
print(alphanumeric)
print(alphanumeric[0][2])
## output
# ['a', 'b', 'c', 'z', 0, 1, 2, 9]
# 1
# [['a', 'b', 'c', 'd'], [0, 1, 2, 9]]
# c
The syntax for the multidimensional list is list[a][b]
, where a
is the outer list and b
is the inner list or iterable
.
Tuples in Python are immutable sequences of data that cannot be modified after they are created. Similar to lists, tuples can contain different data types and the elements are accessed using indexing.
Tuples are created using the built-in tuple function that takes in an iterable
. They are also created with or without the use of parentheses containing the tuple element. A tuple can also contain a single element, but the element must have a trailing comma for it to be a tuple.
# Tuples
# empty tuple
empty = ()
print(empty)
# singleton tuple
single = 2,
print(single)
# tuple with strings
string_tuple = ('Hello',)
print(string_tuple)
# tuple from list
_list = [1, 2, 3]
list_tuple = tuple(_list)
print(list_tuple)
# nested tuple
tuple_a = ('a', 'b', 'c')
tuple_b = (1, 2, 3)
combined = (tuple_a, tuple_b)
print(combined)
## output
# ()
# (2,)
# ('Hello',)
# (1, 2, 3)
# (('a', 'b', 'c'), (1, 2, 3))
Python has a bunch of built-in types that you can checkout here. While these types are handy to use and provides basic functionalities, Python also allow you to write your own data structures that can be used as types and add more custom functionalities to it.
This article discussed the basic data types needed to get you started in your Python journey. To know more about Python built-in data types, checkout the official documentation.
Feel free to drop your thoughts and suggestions in the discussion box. I will be available to attend to them. And also, if you have any questions, you can as well drop them in the discussion box.
20