Topics covered in this post:
Text type is represented in Python by the String object, let's explore that a little further.
String is sequence of Unicode characters. You can represent a string with single ( ''
) or double ( ""
) quotes and for multiple line text you can use a triple quote ( '''
or """
)
s = "This is a single line string"
# output => This is a single line string
print(s)
s = """This is a multiline
string example"""
# output => This is a multiline
# string example
print(s)
Although Strings are immutable, the slicing operator []
can be used with Strings.
# find a character by index
s = 'string sample'
print(s[5]) # output => 'g'
# slicing
print(s[7:]) # output => 'sample'
# string is immutable
s[2] = 'o' # output => TypeError: 'str' object does not support item assignment
In Python 3, Integers can be of any length, but it is constrained only by the memory available.
x = 123456789876543212345678
type(x) # output => <class 'int'>
A float is written with a decimal point e.g 4.5
is a float whilst 4
is a digit. A floating point number is accurate up to 15-16 decimal places, although most say 15 to be safer.
# Output truncated
x = 0.1234567890987654321
print(x) # output => 0.12345678909876544
type(x) # output => <class 'float'>
Complex numbers are used in applications related to mathematics, you write complex numbers in the form of x + yj
, where x
is the real number and y
is the imaginary number. Below is an example:
# complex number
x = 1+2j
type(x) # output => <class 'complex'>
Wondering what real world application of complex numbers could be? check out some comments on this topic here
A list
is a data type that holds a collection of ordered mutable items. mutable means that once the list is created it can be changed, you can add more to it or remove from the list. Below is an example of a list being used.
# slicing a list
x = [10, 2.5, 'hello']
x[1] # output => 2.5
x[1:3] # output => [2.5, 'hello']
# list is mutable
x[2] = 'Python'
x # output => [10, 2.5, 'Python']
You can read more about lists here: python-list-data-structure-practical-example
Tuple data type is a list of values separated by a comma, just like a list, the difference is that a Tuple is immutable, you cannot modify tuples directly after it is created.
# Tuples
# Empty tuple
tuple = ()
# tuple can hold heterogeneous (different) data types
tuple = ("cat", [4, 3, 2], (1, 2, 3))
# Plain comma-separated values are tuples by default
tuple = 1234, 4321, 'hello!'
# single tuple
tuple = 'hello', # <== note trailing comma
# Attempt to change the immutable type
fruits[0] = 'pear' # output => TypeError: 'tuple' object does not support item assignment
You can read more about tuples here: python-tuple-data-structure-practical-example
The range()
function returns a sequence of numbers, starting from 0 as default and incrementing by also by default, it stops before a specified number, the full function signature is: range
(start, stop, step
)
Specifying a step will use that as the increment value, let's explore this with some examples below:
# output => 0 to 9
x = range(10)
for n in x:
print(n)
# output => 1 3 5 7 9
x = range(1, 11, 2)
for n in x:
print(n)
Python dictionary is an unordered collection of key/value pair, imagine this to be an address book where you need to know a person name (key) in order to retrieve their full information.
# empty dictionary
dict = {}
# dictionary with key and value
dict = {'name': 'Kingsley', 'age': 37}
# access with []
dict['name'] # output => 'Kingsley'
# access using get()
dict.get('age') # output => 37
# update value
dict['age'] = 26
print(dict) # => {'name': 'Kingsley', 'age': 26}
You can read more about dictionary here: python-dictionary-data-structure-practical-example
A set
is an unordered collection with no duplicate elements, although mutable, and can have different types (integer, tuple, string etc). It cannot contain mutable elements such as lists
, or dictionaries
as its elements.
# Different of set types in Python
# integers
set = {1, 2, 3}
# mixed data types
set = {3.2, "Hi", (1, 2, 3)}
# check type
type(set) # output => <class 'set'>
You can read more about set here: python-set-data-structure-practical-example
Python 3 provides a Boolean data type. Objects of Boolean type can return one of two possible values: True
or False
type(True) # output => <class 'bool'>
type(False) # output => <class 'bool'>
# boolean as numbers
True == 1 # output => True
False == 0 # output => True
True == 0 # output => False
False == 1 # output => False
# interesting logic
True + True # output => 2
# not boolean operator
not True # ouput => False
# and boolean operator
True and False # ouput => False
True and True # ouput => True
False and False # ouput => False
# or boolean operator
True or False # ouput => True
True or True # ouput => True
False or False # ouput => False
A byte is a unit of data that is eight binary digits long. A byte is the unit most computers use to represent a character such as a letter, number or typographic symbol. Each byte holds a string of bits.
Bytes method returns an immutable bytes object with a given size and data
string = "ABC"
# string with encoding 'utf-8'
arr = bytes(string, 'utf-8')
arr # output => b'ABC'
# test for not mutable
arr[0] = 90 # output => TypeError: 'bytes' object does not support item assignment
bytearray()
method returns a bytearray object which is mutable (can be modified) the returned sequence of integers is in the range 0 <= x < 256.
string = "ABC"
# string with encoding 'utf-8'
arr = bytearray(string, 'utf-8')
arr # output => b'ABC'
# test mutable with ASCII 90 (Z)
arr[0] = 90
arr # output => bytearray(b'ZBC')
The memoryview()
function returns a memory view object for given argument, it makes it possible to access the internal buffers of an object by creating a memory view object.
Whenever we perform an action on an object such as call a method or slice an array, Python in the background creates a copy of the object., if we are dealing with large data, creating copies would be a great cost in memory and slow down execution speed.
With buffer protocol, we can give another object access to data without copying it.
byte_array = bytearray('ABC', 'utf-8')
print('Before update:', byte_array) # output => Before update: bytearray(b'ABC')
mv = memoryview(byte_array)
# update 1st index of mv to Z
mv[1] = 90
print('After update:', byte_array) # output => Before update: bytearray(b'AZC')
The ASCII value of Z is 90, we use that to swap content of the mv in 1st index position, since the memory view object references the same memory/buffer of byte_array, the byte_array value is automatically updated. to AZC
This concludes the overview look on Python's data types, for every variable we create it is important to know what data type we save into it and also know the methods required to manipulate each data type.