You are on page 1of 20

PYTHON TUPLES,

DICTIONARY AND
ARRAY

Dr Nurbiha A Shukor

2020
FAKULTI SAINS SOSIAL & KEMANUSIAAN
SEKOLAH PENDIDIKAN 1
Learning Outcomes
At the end of this lesson, students should be able to:

 Differentiate between list, tuples and dictionary


 Create tuples and manipulate tuples
 Create dictionary and manipulate dictionary
 Explain concept of array in Python

2
PYTHON TUPLES

2020
FAKULTI SAINS SOSIAL & KEMANUSIAAN
SEKOLAH PENDIDIKAN 3
Tuples
 A tuple is a sequence data type that can contain elements of
different data types similar to list.
 Tuples are different from lists because tuples are
immutable/cannot be changed.
 You can’t modify the elements of a tuple, but you can
replace one tuple with another.

t = ('a', 'b', 'c', 'd', 'e')


t = ('A',) + t[1:]
print(t)

4
Accessing elements in Tuple
 Access element in tuple using indexes (run the codes in
Command Prompt or Run Console in Trinket)
elementary_grades=(2,3,4)

>>>Elementary_grades[0]
2
>>>elementary_grades[:2]
(2,3)
>>>elementary_grades[-1]
4

5
Working with Tuples
 A tuple literal is defined in one of three ways:
 A single element followed by a comma ,
 Multiple elements separated by commas
 An empty set of parentheses ( )
tuple1 = "hello world"
tuple2 = ("hello world")
tuple3 = ("hello", "world")
tuple4 = "hello", "world"
tuple5 = ()

print (tuple1)
print (tuple2)
print (tuple3)
print (tuple4)
print (tuple5 + tuple3)

6
Working with Tuples
 Operator on a single-element tuple and on an
integer.
tuple_1 = (3,)
print (tuple_1 * 3)

tuple_2 = (3)
print (tuple_2 * 3)

 Indexing, Slicing and Measuring


negeri = ("johor", "melaka", "kedah", "selangor")
print (negeri)
print (negeri [2])
print (negeri [0:2])
print (len (negeri))

7
Lists VS Tuples
Guido (Python's creator) and the Python community promote
the following conventions for choosing between lists and
tuples:

Heterogeneous and Tuples for sequence Tuples for some Lists for mutable
homogeneous data keys functions objects
• Tuples for • If you need to use a • Some functions • Avoid using mutable
heterogeneous data, sequence as a require arguments to objects in immutable
lists for dictionary key, you be passed in tuples. containers because
homogeneous data. must use a tuple errors and
• Use a tuple if your because dictionary unexpected results
data includes several keys are immutable. can occur if you
different data types, attempt to change
such as names and the mutable objects.
addresses.
• Use lists for
elements that are all
of the same type.

8
PYTHON DICTIONARY

2020
FAKULTI SAINS SOSIAL & KEMANUSIAAN
SEKOLAH PENDIDIKAN 9
Dictionary in Python
 Similar to list, dictionary allows many values to be stored in
1 variable.
 List has element assigned by index that was assigned from
0 but dictionary uses key associated with the indexing.
 The key can be formed with combination of characters and
can be empty string.
 The key has to be associated with values which forms key-
value pair.

10
Creating a Dictionary
 Create a variable name
 Use assignment statement to assign key-value pair and
open-close braces, { }
 Create Key-value pair separated by colon key:value
 Separate each element using comma

nilai_maths = {‘pi’:3.14, ‘e’:2.71, ‘root 2’:1.41}

11
Accessing elements in dictionary
kamus_negeri = {"johor":"johor bahru", "pahang":"kuantan"}
print ("Ibu negeri johor adalah ", kamus_negeri ["johor"])

Calling the name for the dictionary

Calling the key in the kamus_negeri dictionary

12
Adding/Removing key-values in dictionary
kamus_buah = {}
kamus_negeri = {"johor":"johor bahru", "pahang":"kuantan"}
kamus_jantina = {1:"lelaki" , 2:"perempuan"}

kamus_negeri ["kelantan"] = "kota bharu"


print (kamus_negeri)
del kamus_negeri ["pahang"]
print (kamus_negeri)

print (kamus_jantina [1])

kamus_buah ["durian"] = "RM25 sekilo"


print (kamus_buah)

13
Working with Dictionaries
kamus_buah = {}
kamus_negeri = {"johor":"johor bahru", "pahang":"kuantan"}
kamus_jantina = {1:"lelaki" , 2:"perempuan"}
print ("Ibu negeri johor adalah ", kamus_negeri ["johor"])

kamus_negeri ["kelantan"] = "kota bharu"


print (kamus_negeri)
del kamus_negeri ["pahang"]
print (kamus_negeri)
print (kamus_jantina [1])
kamus_buah ["durian"] = "RM25 sekilo"
print (kamus_buah)

print (kamus_negeri.keys())
print (kamus_negeri.values())
print (kamus_negeri.items())
14
Additional operations in dictionary
 Adding key-value pair by user
 Start with empty dictionary
 Count how many key-value pairs are there in a dictionary:
 Using len()
 Identify/Check if a key/value is already in the dictionary:
 Use ‘in’ operator to check key
 Use ‘in’ operator and ‘values’ to check is a value is
present in a dictionary
if x in d.values():
print (‘At least one of the values in d are’, x)
else:
print (‘None of values in d are’, x)

15
Loop in Dictionary
 Loop can be used to iterate all the values in the dictionary
 Example:

constant = {‘pi’:3.14, ‘e’:2.71, ‘root 2’:1.41}

for k in constant:
print (‘The value associated with’, k, ‘is’, constant [k])

16
Practice Example
 Create a program that determines and display the number
of unique characters in a string entered by user. For
example, Hello, World! Has 10 unique characters and zzz
has one unique character. Use dictionary to solve this
problem.
#Read string from user
s=input('Please insert a string:')

#Create a dictionary
characters={}
for ch in s:
characters[ch]=True

#display result
print('The number of unique character in', s, 'is', len(characters))

17
Exercise 1
 In the game of Scrabble, each letter has appoint associated
to it. The total score of a word is the sum of the scores of its
letters. The points associated with each letter are shown
below: Points Letters

1 A, E,I, L, N, O, R, S, T and U

2 D and G

3 B,C, M and P

4 F, H,V, W and Y

5 K

8 J and X

10 Q and Z

Write a program that computes and display the Scrabble score


for a word. Create a dictionary that maps from letters to point
values. Then use the dictionary to compute the score.
18
PYTHON ARRAY

2020
FAKULTI SAINS SOSIAL & KEMANUSIAAN
SEKOLAH PENDIDIKAN 19
Array
 Arrays are used to store multiple values in one single variable.
 Python does not have built-in support for Arrays, but Python
Lists can be used instead.
 Python has a set of built-in methods that you can use on
lists/arrays.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list 20

You might also like