Python Tutorial

Data Structures:

This page can be downloaded as interactive jupyter notebook

An additional quiz about the contents of this tutorial, can be downloaded here (with solutions)

Datatypes in Python:

In python, we have different types of data. In this chapter, you will learn these data types, conversion between data types and mathematical operations. The data types are in the following list:

  • Numbers
  • String
  • Dictionary
  • List
  • Tuple
  • Set

Number Data Type

Python supports integer, float and complex numbers. You can define them as int, float and complex class in python.

Integer and float numbers are seperated by the presence or absence of a decimal point. For example, 5 is an integer number whereas 5.0 is a float number.

Complex numbers are written in this form, x + yj, where x is the real part and y is the imaginary part of the complex number.

In python, we have two functions to know the variable is in which class. We can know the class of a variable by using type() function and check a variable belongs to a class or not by using isinstance() function. In the following example, you can see how these functions work.

Example: Assign a variable and get the class of variables. Please change the number, run the program and see the result.

# Assign a variable

x = 585

# Check the class of variable
print(type(x))

# Check tha variable is complex or not
print(isinstance(x,complex))
<class 'int'>
False

Note: Integer value can be of any length, but a float number is accurate only up to 15 decimal places.

Type Conversion

In python, we can convert the numbers from one type into another type. We can do it by using built-in functions like int(), float(), complex() and string str() to convert between types.

Example: Conversion between number types.

# Convert float to integer
a = int(5.6)
print(type(a))

# Convert string to float
b = float('22.55')
print(type(b))

# Convert string to complex
c = complex('5')
print(type(c))
<class 'int'>
<class 'float'>
<class 'complex'>

Note: Operations like addition and subtraction, convert integer to float autimatically, if one of the operands is float.

Example: Conversion in operations.

# Add an integer number with a float number
x = 2 + 3.0
print(type(x))

# Subtract between an integer number and a float number
y = 8.0 - 4
print(type(y))
<class 'float'>
<class 'float'>

Python decimal

Sometimes python perform some amazing float class calculation. For better understanding, please run and check this code below.

# float calculation

(1.1 + 2.2) == 3.3

False

What is going on? It turns out because the numbers are stored in computer as binary fractions and the computer just can understand binary (0 and 1). Due to this reason, most of the decimal fraction we know cannot be stored accurately in the computer.

All we know mathematically the result of the summ of two float numbers 1.1 and 2.2 is accurately 3.3.But, let’s run the code below to see the result of the summ of two float number in computer.

# Sum of the two float numbers

result = 1.1 + 2.2

print(result)
3.3000000000000003

The 0.1 value in binary will be an infinity long binary fraction of 0.000110011001100110011... and the computer only stores a finit number of it. This will approximate 0.1 but never be equal. Hence, it is the limitation of the computer not python.

Python has decimal module that we can use it to overcome this issue. The decimal module has user settable precision, it means we can import it and set the precision of the float nembers in our program.

Example: Let’s run the code below and see the differences.

# Using decimal module

import decimal
print(0.1)
print(decimal.Decimal(0.1))

# Sum two float number

print(1.1 + 2.2)
print(decimal.Decimal('1.1') + decimal.Decimal('2.2'))

# Multiply two float number

print(1.2 * 2.50)
print(decimal.Decimal('1.2') * decimal.Decimal('2.50'))
0.1
0.1000000000000000055511151231257827021181583404541015625
3.3000000000000003
3.3
3.0
3.000

When we use Decimal instead of float?

We do not use Decimal every time, because of efficiency in programming. We generally use Decimal in special cases that you can see some of them in following:

  • When we want to create financial applications that need exact decimal representation.
  • When we need to control the level of precision.
  • When we want to implement the notion of significant decimal places.
  • When we want to have the result from operations to be like that we expect(1.1 + 2.2 = 3.3)

Python Fraction

A fraction has two parts. It contains a numerator and a denominator, both parts are integer. Python provides operations involving fractional numbers through its fraction module. This module support rational number arithmetric.

We can create Fraction objects in various ways. You can see some example in the following.

Example: Create some Fraction objects.

# import the module
import fractions

# Create fraction
print(fractions.Fraction(2.5))

print(fractions.Fraction(5))

print(fractions.Fraction(5,8))
5/2
5
5/8

Note: In python, Fraction allows us to instantiate with string as well. We prefer this option when using decimal numbers in creating Fraction object.

You can see somple examples below to get more familiar with creation of Fractions in python.

Example: Let’s run the codes below and check the result.

# import the module
import fractions

# As float
print(fractions.Fraction(1.1))

# As string
print(fractions.Fraction('1.1'))
2476979795053773/2251799813685248
11/10

Fractions support all basic operations. Here are few examples.

# import the module
from fractions import Fraction as F

# sum
print(F(2,5) + F(1,5))

# divide
print(1 / F(2,3))

# True or False
print(F(-5,5) > 0)

print(F(-5,5) < 0)
3/5
3/2
False
True

Python Mathematics

Python offers modules like math to carry out different mathematics operations, like trigonometry, logarithm, probability and statistics, etc.

Example: Here you can see some example of using math module.

# import the module
import math

# get Pi value
print(math.pi)

# trigonometric calculation
print(math.sin(math.pi))

# exponential calculation
print(math.exp(1))

# logarithmic calculation
print(math.log10(1000))

# trigonometric calculation
print(math.sinh(1))

# getting the factorial
print(math.factorial(10))
3.141592653589793
1.2246467991473532e-16
2.718281828459045
3.0
1.1752011936438014
3628800

String

A string is a sequence of characters.

How to create a string in python

In python, we can create a string by enclosing characters inside a double quotes"" or single quote'' . Even triple quotes can be used, but generally it is used to represent multiline string and docstring.

Example: Let’s see some example of string.

# create same string in three different way

my_string = 'Hello'
print(my_string)

my_string = "Hello"
print(my_string)

my_string = '''Hello'''
print(my_string)

# triple quotes string can be in multiple lines
my_string = """Hello, welcome to the
            world of python"""
print(my_string)
Hello
Hello
Hello
Hello, welcome to the
            world of python

How to access characters in a string

We can access to a string’s characters by indexing and a range of characters using slicing(operator colon). In string, Like list, index must be integer and it starts from 0. Also we have negative indexing in strings.

Example: Let’s see some example of string indexing and slicing.

# Indexing string characters
str1 = 'Geoinformatics'

# last character
print('str1[-1]:' ,str1[-1])

# sixth character
print('str1[5]:' ,str1[5])

# slicing first to 5th character
print('str1[0:5]:' ,str1[0:5])

str1[-1]: s
str1[5]: f
str1[0:5]: Geoin

Delete or change a string

Strings are immutable like tuples. It means, we can not change the characters or assign a new character. We do not have access to delete a character from a string, but we can remove a string using del.

String Operations

Concatenation of two or more strings

Concatenation is joining of two or more strings into a single one. We can use + operator to concatenate strings in python.

Note: We can use * operator to repeat the string for a given number of times.

Example: Let’s run the code to see operation of concatenation and repeat strings.

# Assign strings
str_1 = 'Geodesy'
str_2 = 'And'
str_3 = 'Geoinformatics'

# Concatenation
print(str_1 + str_2 + str_3)

# Repaet
print(str_1 * 3)
GeodesyAndGeoinformatics
GeodesyGeodesyGeodesy
str = 'Leibniz'

# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)

#character count
print('len(str) = ', len(str))
list(enumerate(str) =  [(0, 'L'), (1, 'e'), (2, 'i'), (3, 'b'), (4, 'n'), (5, 'i'), (6, 'z')]
len(str) =  7

Note: enumerate() is a built-in function that returns a list which contains index and value of the string. len() is also a built-in function that returns length of the string.

Example: Here you can see how enumerate() function works.

# enumerate a string
my_string = 'ICAML'

list_enumerate = list(enumerate(my_string))
print('My string contains: ',list_enumerate)
My string contains:  [(0, 'I'), (1, 'C'), (2, 'A'), (3, 'M'), (4, 'L')]

Dictionaries

In python, dictionaries are an unordered collection of elements. Elements in dictionaries are indexed by keys. The keys can be any immutable type, like string and numbers. Dictionaries are useful to retrieve values when the keys are known.

Create a dictionary

In python, we can create a dictionary very simple as placing elements inside curly braces {} separated by comma.

In dictionaries, any item has a key. key:value

Keys must be immutable data types (string, number or tuple with immutable elements) and must be unique, while values can be any data type and can repeat.

Example: Let’s see some example of creating dictionaries.

# create an empty dictionary
dict_1 = {}

# dictionary with integer keys
dict_2 = {1: 'red', 2:'green', 3:'blue'}
print(dict_2)

# dictionary with mixed keys
dict_3 = {'R': 'red', 'G':'green', 'B':'blue', 1:'yellow', 2:'gray'}
print(dict_3)

# Create dictionary using function
dict_4 = dict({1: 'red', 2:'green', 3:'blue'})
print(dict_4)

# from sequence having each item as a pair
dict_5 = dict([(1,'red'), (2,'green'), (3,'blue')])
print(dict_5)
{1: 'red', 2: 'green', 3: 'blue'}
{'R': 'red', 'G': 'green', 'B': 'blue', 1: 'yellow', 2: 'gray'}
{1: 'red', 2: 'green', 3: 'blue'}
{1: 'red', 2: 'green', 3: 'blue'}

Access to a dictionary’s elements

In dictionaries, we have access to elements using keys inside square brackets or with the get() method.

Example: Here is example of access to the dictionary’s elements.

my_dict = {1: 'red', 2:'green', 'B':'blue'}

print(my_dict[2])

print(my_dict.get('B'))
green
blue

Change or add elements in a dictionary

We can add a new item or change current items using assignment operator.

Example: Here is example of assignment operators on a dictionary.

my_dict = {1: 'red', 2:'green', 3:'gray'}

# add new item
my_dict[4] = 'black'
print(my_dict)

# update value
my_dict[3] = 'blue'
print(my_dict)
{1: 'red', 2: 'green', 3: 'gray', 4: 'black'}
{1: 'red', 2: 'green', 3: 'blue', 4: 'black'}

Delete or remove items from a dictionary

We can remove an individual items from a dictionary using del and remove all items using clear().

Example: Here is example of remove or delete items from dictionary.

# Create a dictionary
my_dict = {1: 'red', 2:'green', 3:'gray'}

# Delete an item
del my_dict[1]
print(my_dict)

# Remove all items
my_dict.clear()
print(my_dict)
{2: 'green', 3: 'gray'}
{}

Dictionary Methods

Here you can see a list of methods which used in python to work with dictionaries.

clear(): Remove all items form the dictionary.

copy(): Return a shallow copy of the dictionary.

fromkeys(seq[,v]): Return a new dictionary with keys from seq and value equal to v (defaults to None).

get(key[,d}): Return the value of key. If key does not exit, return d (defaults to None).

items(): Return a new view of the dictionary’s items (key, value).

keys(): Return a new view of the dictionary’s keys.

pop(key[,d]): Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found, raises KeyError.

popitem(): Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty.

setdefault(key[,d]): If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None).

update([other]): Update the dictionary with the key/value pairs from other, overwriting existing keys.

values(): Return a new view of the dictionary’s values

Dictionary Comprehension

Dictionary comprehension is an elegant way to create a dictionary.

Example: Here you can see how dictionary comprehension works.

# Create dictionary
dict_new = {i: i*2 for i in range(5)}
print(dict_new)
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}

Python List

Python offers many datatypes often reffered to as sequences. Most frequently used is the List which can be written as a list of values between square brackets. We use comma to seperate values in a list. Lists can have any number of items and might contain items of different types.

Also, a list can even have another list as an item. This is called nested list.

Example: Here you can see some examples of creating lists.

# empty list
first_list = []
print(first_list)

# List of odd number
odd_list = [1 , 3 , 5 , 7 , 9]
print(odd_list)

# List of mixed data types
mixed_list = [55 , 3.14 , "Hello"]
print(mixed_list)
[]
[1, 3, 5, 7, 9]
[55, 3.14, 'Hello']

How to access elements of the list:

Lists can be indexed and sliced. All slice operations return a new list that contains all requested elements. Also List supports operations like concatenation.

Example: Here you can see some examples of indexing, slicing and concatinate lists.

# Index the list
print(odd_list[3])

# Slicing List
print(odd_list[0:2])

# Concatinate List
print(odd_list + [11 , 13 , 15 , 17])
7
[1, 3]
[1, 3, 5, 7, 9, 11, 13, 15, 17]

Exercise: Program a code to take a list of numbers and make a new list with cube value of the items.

# Create a list with cube values of the input numbers

# Input list
input_list = [1 , 2 , 3 , 4 , 5]

# Create a new list with cube values
new_list = []

# Print the result
print(new_list)

Negative indexing

Python allows negative indexing for its sequence. The index of -1 refers to the last item, -2 to the second last item and so on.

Exercise: Let’s to index lists by negative indexing. compute addition of odd numbers of the input list by negative indexing.

# Negative indexing

# Input list
my_list = [11 , 13 , 15 , 17 , 19]

# compute addition
addition_result = 


How to change or add elements to a list

We can use assignment operator = to change an item or a range of items. And we can add a new item to a list using append() method or add several items using extend() method.

Example:

# Input list - incorrect values
even_list = [1 , 3 , 5 , 7 , 9]

# change the fist item
even_list[0] = 2
print(even_list)

# change second to fifth items
even_list[1:5] = [4,6,8,10]
print(even_list)

# Add item
even_list.append(12)
print(even_list)

# extend list
even_list.extend([14,16,18])
print(even_list)
[2, 3, 5, 7, 9]
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10, 12]
[2, 4, 6, 8, 10, 12, 14, 16, 18]

Note: We can use +operator to combine two lists. This is called concatination.

Note: We can use * operator to repeat a list for the given number of times.

Example:

# concatination
print(even_list + [20 , 22])

# repeat
print([1 , 2] * 3)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
[1, 2, 1, 2, 1, 2]

How to delete or remove items from a list

In python, we have several methods to do it. You can see some of them here;

del: It deletes one or more items from the list.

remove(): It removes any item from the list.

pop(): It removes the item at the given index.

clear(): We can use it to empty a lst.

Examples:

li_st = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9]

# Delete one item
del li_st[1]
print(li_st)

# Remove an item
li_st.remove(9)
print(li_st)

# pop an item from the list
li_st.pop(0)
print(li_st)

# empty the list
li_st.clear()
print(li_st)
[1, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 4, 5, 6, 7, 8]
[3, 4, 5, 6, 7, 8]
[]

Python list methods

append() Add an element to the end of the list

extend() Add all elements of a list to the another list

insert() Insert an item at the defined index

remove() Removes an item from the list

pop() Removes and returns an element at the given index

clear() Removes all items from the list

index() Return the index of the first matched item

count() Return the count of number of items passed as an argument

sort() Sort items in a list in ascending order

reverse() Reverse the order of items in the list

copy() Returns a shallow copy of the list

cmp(list1,list2) Compares elements of both lists

len() Gives the length of the list

max() Returns the maximum value from the list

min() Returns minimum value from the list

list() Convert a tuple into list

Exercise: Let’s complete the code below by python list methods.

# List methods applications

# Input lists
first_list = [0,1,2,3,4]
second_list = [6,7,8,9]

# add all elements of second list to the first list
third_list = 
print(third_list)

# add numbers 5 and 10 at the correct place in sequence to the third_list


print(third_list)

# reverse the sequnce of the numbers in the third_list

print(third_list)

# remove the last item from the third_list

print(third_list)

# Make a copy of the list
forth_list = 
print(forth_list)

# Clear the third_list


# count the items of the forth_list


List Comprehension

This is a very usefull and elegent way to create a new list in python. It consist of an expression to create a subsequence of the elements which satisfy a certain condition.

Example: Let’s run the programm below to see the result of list comprehension.

# create a list of squared numbers
sqr_num = [i ** 2 for i in range(10)]
print(sqr_num)

# create a list of even numbers
even_list = []
for x in range(10):
    even_list.append(2 * x)
    
print(even_list)

# create a list of power of two
power_2 = list(map(lambda a: 2**a, range(10)))
print(power_2)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

Python Tuple

Tuple is a standard sequence data type in python. It consists of elements separated by commas.

Example: Here you can see some example of creating tuple in python.

# tuple with mixed elements
tuple_1 = 159, 'Hello', 753
print(tuple_1)

# tuple with integer
tuple_2 = (1, 2, 3)
print(tuple_2)

# nested tuple
tuple_3 = ('pyhton',tuple_1,tuple_2)
print(tuple_3)
(159, 'Hello', 753)
(1, 2, 3)
('pyhton', (159, 'Hello', 753), (1, 2, 3))

Note: Tuples are immutable. The tuple object does not support item assignment. It is impossible to change or delete (remove) tuple elements.

Example: Let’s run the programm to check the code result.

t = (123, 456, 789)
t[0] = 888
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-50-36141be006eb> in <module>()
      1 t = (123, 456, 789)
----> 2 t[0] = 888


TypeError: 'tuple' object does not support item assignment

How to access elements of a tuple:

Accessing elements in Tuple is too similar to the accessing elements in List. In the following examples, you can see different access way to tuple elements.

Example: Tuple elements access methods.

# Create a tuple
my_tuple = (1, 2, 3, 4, 5, 6)

# Indexing
print(my_tuple[0])

# Negative Indexing
print(my_tuple[-1])

#Slicing
print(my_tuple[0:4])

#Delete
del my_tuple

1
6
(1, 2, 3, 4)

Tuple Methods

For Tuple, methods that add, remove or change items are not available. There is some other methods that works in Tuple.

count(x) Return the number of items that is equal to x

index(x) Return index of first item that is equal to x

all() If all elements in a tuple are true, it returns True

enumerate() Return an enumerate object.

len() Returns the number of items in a tuple.

max() Returns the largest item in a tuple.

min() Returns the minimum item in a tuple.

sorted() Takes elements in the tuple and returns a new sorted list.

sum() Returns the sum of all items in a tuple.

tuple() Convert a variable like list, string, set or dictionary to a tuple.

Note: An enumerate object contains the index and value of all the items of tuple as pairs.

Example: Let’s to see example of tuple methods.

# create a tuple
T = ('a', 'b', 'c', 'd', 'b', 'b')

# count
print(T.count('b'))

# index
print(T.index('c'))
3
2

Sets

A set is an unordered collections of elements which are unique and immutable. We cannot change elements in sets but we can add or remove elements from it.

Sets are used mostly to perform mathematical operations like intersection, union and symmetric difference.

How to create a set

In python, a set is created by placing elements between curly braces {} and separating elements using comma , or using the function set().

Note: We cannot use empty {} to create an empty set, because the empty {} creates an empty dictionary. But it is possible to create an empty set using set() function without any argument.

Example: Here is some different example of set creation.

# Create set

# set of strings
first_set = {'a', 'b', 'c', 'd'}
print(first_set)

# set of integer
second_set = set([1, 2, 3, 4, 5])
print(second_set)

# set of mixed datatype
third_set = {5, 'python', 3.5, (5,3,9)}
print(third_set)

# Empty set
emp_set = set()
print(emp_set)
{'b', 'd', 'a', 'c'}
{1, 2, 3, 4, 5}
{(5, 3, 9), 3.5, 'python', 5}
set()

Remove, change or add elements in sets

Indexing is impossible in sets, because sets are unordered. And we cannot change elements in sets, because sets are immutable. But we have some useful methods to add or remove element in/from a set.

add(): Add new elements to a set

update(): It takes tuples, lists, strings or sets as argument, then update elements inside of the set.

discard() or remove(): Remove a particular item from a set.

clear(): Removes all items from the set.

Example: Here you can see application of these methods on sets.

my_set = {1,4}
print(my_set)

# Add an element
my_set.add(2)
print(my_set)

# Update the set by a list
my_set.update([2,3,4,6])
print(my_set)

# Update the set by another set
my_set.update({5,6,7})
print(my_set)

# Remove item from set
my_set.discard(7)
print(my_set)

my_set.remove(1)
print(my_set)

{1, 4}
{1, 2, 4}
{1, 2, 3, 4, 6}
{1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6}
{2, 3, 4, 5, 6}

Set operators

Sets can be used to carry out mathematical set operations like intersection, union, difference and symmetric difference. Let us to explain these operations in a example.

Example: Application of set operations.

# Input sets
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# Union: is a set of all elements of two sets (operator is |)
print('The union is: ',A | B)
C = A.union(B)
print('A.union(B):',C)
D = B.union(A)
print('B.union(A):',D)

# Intersection: interection of `A` and `B` is a set that contains common elements from both sets
print('Intersection is: ', A & B)
E = A.intersection(B)
print('A.intersection(B): ',E)
F = B.intersection(A)
print('B.intersection(A):',F)

# Difference: difference of `A` and `B` is a set that contains elements which are only in `A` not in `B`.
print('Difference is: ', A - B)
G = A.difference(B)
print('A.difference(B): ',G)
H = B.difference(A)
print('B.difference(A): ',H)

# Symmetric difference: Symmetric difference of `A` and `B` is a set of elements in both `A` and `B` except those that are common n both.
print('Symmetric difference is: ', A ^ B)
I = A.symmetric_difference(B)
print('A.symmetric_difference(B): ',I)
J = B.symmetric_difference(A)
print('B.symmetric_difference(A): ',J)
The union is:  {1, 2, 3, 4, 5, 6, 7, 8}
A.union(B): {1, 2, 3, 4, 5, 6, 7, 8}
B.union(A): {1, 2, 3, 4, 5, 6, 7, 8}
Intersection is:  {4, 5}
A.intersection(B):  {4, 5}
B.intersection(A): {4, 5}
Difference is:  {1, 2, 3}
A.difference(B):  {1, 2, 3}
B.difference(A):  {8, 6, 7}
Symmetric difference is:  {1, 2, 3, 6, 7, 8}
A.symmetric_difference(B):  {1, 2, 3, 6, 7, 8}
B.symmetric_difference(A):  {1, 2, 3, 6, 7, 8}

Python set methods

In the following list, you can see many set methods which are useful in programming with python.

add(): Add an element to the set

clear(): Removes all items from a set

copy(): Returns a copy of the set

difference(): Returns the difference of two or more sets as a new set

difference_update(): Removes all elements of another set from this set

discard(): Removes an element from the set if it is a member. (Do nothing if the element is not in set)

intersection(): Returns the intersection of two sets as a new set

intersection_update(): Updates the set with the intersection of itself and another

isdisjoint(): Returns True if two sets have a null intersection

issubset(): Returns True if another set contains this set

issuperset(): Returns True if this set contains another set

pop(): Removes and returns an arbitrary set element. Raise KeyError if the set is empty

remove(): Removes an element from the set. If the element is not a member, raise a KeyError

symmetric_difference(): Returns the symmetric difference of two sets as a new set

symmetric_difference_update(): Updates a set with the symmetric difference of itself and another

union(): Returns the union of sets in a new set

update(): Updates the set with the union of itself and others


Author: Mohsen Soleymanighezelgechi
Last modified: 02.06.2019