You are on page 1of 15

UNIT 9.

Python
What is Python?
Python Data Structure
An array is a data structure which holds a set of
data items of the same data type. In a program,
an array has a name, length (representing the
number of data items to be stored) and a data
type defined by the programmer.
Using lists in Python

• The data structures in Python are called lists


and tuples. These are very similar to arrays –
the main difference is that arrays can only
hold data items of the same data type,
whereas lists and tuples can hold mixed data
types.
A tuple is a list which cannot be edited once it is
created in Python code – the data in the tuple
cannot be changed. The data in a list, however,
can be altered at any time.

The code attempts to change the name of the last


animal to ‘elephant’, but an error occurs as the
contents of a tuple cannot be changed.
Note that tuples use round brackets ( ) to enclose data
This Python code creates a list called listanimals
and prints the contents of the list onto the
screen. The code then changes the name of the
last animal to ‘elephant’, using the statement
listanimals[2] = ‘elephant’.
Note that lists use square brackets [ ] to enclose data
INSERTION SORT
BUBBLE SORT
How it works?
We can do this using the bubble sort method,
which is made up of numerous comparisons.
Each comparison examines two adjacent
elements in the array of data. If they are out of
order then the code swaps their position around.
One full pass is when each item of data has been
compared to each of its neighbours once.
In this list, a full pass consists of five comparisons.
The table below shows the results after one full
pass through the array of data.
Create code
Create code
runTimes = [18.59, 19.21, 17.33, 19.88, 20.09, 20.51]
for i in range (0, 5):
for j in range (0, 5 - i):
if runTimes [ j ] > runTimes [ j + 1 ]: Loop for
temp = runTimes [ j ] comparison
runTimes [ j ] = runTimes[ j + 1 ] between
adjacent items
runTimes [ j + 1 ] = temp

# Print runTimes array after every pass


print ("After pass " + str ( i + 1 ) + ":")
print (runTimes)

print("The sorted list:")


print(runTimes)
Insertion Sort coding
mylist = [16,3,4,7,1,9]
for index in range(1 , len(mylist)):

Using FOR loop

(1 , len(mylist))
* Start with index position 1 because we will start comparing from
2nd item of the list
mylist = [16,3,4,7,1,9]
Sorted Unsorted
Insertion Sort coding
mylist = [16,3,4,7,1,9]
for index in range(1 , len(mylist)):
pos = index
while mylist[pos -1] > mylist[pos] and pos >0:
mylist[pos -1], mylist[pos] = mylist[pos], mylist[pos -1]
pos -= 1
print(mylist)
Activity

• Go to play.blooket.com
• Enter Game ID as shown on the screen

You might also like