0% found this document useful (0 votes)
15 views37 pages

Lecture 11 Python

Python lecture

Uploaded by

abelandenet9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views37 pages

Lecture 11 Python

Python lecture

Uploaded by

abelandenet9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

CSEg 1101 Introduction to Computing

Lecture 11

Fall 2023/24

Computer science and Engineering


The School of EE & Computing
Adama Science & Technology University
ASTU

Data structures (objects composed of another objects):

Tuples
(1, 3, 5, 7, 9)
(“red”, “green”, “blue”)
(777, “a lucky number”)
Strings
Lists
Dictionary

2
ASTU
OUTLINE

Preview: tuples and strings


Lists
Summary: strings, tuples, lists

Reading assignment
Chapters 9 and 11 of the textbook

Note: use python 3.X for to execute the codes

3
ASTU
PREVIEW: TUPLES AND STRINGS

Tuples
A tuple is an ordered sequence of data elements. It is
an immutable object. In other words, a tuple can never
be changed unless it is re-created.

Tup0 = ()
tup1 = (1, 2, 3, 4, 5)
tup2 = (1.57, 3.14, 9.02)
tup3 = (“one”, “two”, “three”)
tup4 = (1, 3.14, “two”., 2, (5, 6))

4
ASTU
Cont …
A singleton tuple
Is (2) a tuple ? Well, ……

Is (2) the same as 2 ?


Yes !
Then, how to express a singleton tuple, e.g., a tuple
containing only 2 as the element?
(2,)

5
ASTU
Cont …
Selection Slicing
>>>tp1 = (1, 2, 3, 4, 5) >>>tp1[1:3]
>>>tp1 (2, 3)
(1, 2, 3, 4, 5) >>>tp1[:3]
>>>tp1[0] (1, 2, 3)
1 >>>tp1[1:]
>>>tp1[2] (2, 3, 4, 5)
3 >>>tp1[:]
>>>tp1[-1] (1, 2, 3, 4, 5)
5 >>>tp1
>>>tp1[-2] (1, 2, 3, 4, 5)
4
6
ASTU
Strings
A string is an ordered sequence of characters. It is an
immutable objects.

st1 = “abcedghijklmnopqrstuvwxyz”
st2 = “0123456789”
St3 = “cce20003 is fantastic !”

>>>st1 + st2 concatenation


‘abcdefghijklmnopqrstuvwxyz0123456789’

7
ASTU
Cont…
Selection Slicing

>>>s1 = “abcdefg” >>>s1[1:3]


‘bc’
>>>s1[0] >>>s1[:3]
‘a’ ‘abc’
>>>s1[2] >>>s1[1:]
‘c’ ‘bcdefg’
>>>s[-1] >>>s1[:]
‘g’ ‘abcdefg’
>>>s[-2] >>>s1
‘f’ ‘abcdefg’

8
ASTU
LISTS
Top 10 Countries in 2012 Summer Olympic Medals
Rank NOC Gold Silver Bronze Total

1 United States 46 29 29 104

2 China 38 27 23 88

3 Great Britain 29 17 19 65

4 Russia 24 25 32 81

5 Rep. of Korea 13 8 7 28

6 Germany 11 19 14 44

7 France 11 11 12 34
8 Italy 8 9 11 28
9 Hungary 8 4 6 18

10 Australia 7 16 12 35
9
ASTU
Cont …
How can we store this much data in Python?
Should we use 4 x 10 variables?

How many variables to store the medal information for all


countries ?

The solution is to store the information in lists.

10
ASTU
Cont …
 A list is an ordered sequence of data elements.
 It is a mutable object. In other words, existing
elements can be replaced and deleted, and new
elements can be added.
 To create a list, enclose the values in square brackets []
list0 = []
list1 = [1, 2, 3, 4, 5]
list2 = [1.57, 3.14, 9.02]
list3 = [“one”, “two”, “three”]
list4 = [1, 3.14, “two”., 2, (5, 6), [7,8]]

11
ASTU
Cont …
 A list is an object of type list.
 We can access the elements of a list using an integer in
dex. The first element is at index 0, the second at index
1, and so on:
>>> countries[0]
‘United States'
>>> countries[9]
‘Australia'
>>> gold[5]
11

12
ASTU
Cont …
 Negative indices start at the end of the list:
>>> countries[-1]
‘Australia'
>>> countries[-5]
‘Germany’
The length of a list is given by len:
>>> len(countries)
10
The empty list is written [] and has length zero.

13
ASTU
Cont …
Now we can store the 2012 Summer Olympic Medal
Table using lists:

countries = [“United States”, “China”, ….. , “Australia”]


golds = [49, 38, ….. , 7]
silvers = [29. 27, ….. . 16]
bronzes = [29, 23, ….., 12]

14
ASTU
Cont…
Selection, slicing, and concatenation are allowed in lists
as in tuples:

>>>counties[4] >>>list1 = countries[0:2]


‘Rep. of Korea” >>>list1
>>>golds[4] [‘United states’, ‘China’]
13 >>>list2 = countries[2:3]
>>>countries[-1] [‘Great Britain’]
‘Australia’ >>>list1 + list2
>>>countries[2:4] [‘United States’, ‘China’,
[‘Great Britain’, ‘Russia’] ‘Great Britain’)]
>>>golds[2:4]
[29, 24]
15
ASTU
Cont…
The function range() generates a list of non-negative integer.

>>>range(0, 10, 2) for i in range(5):


[0, ,2, 4, 6, 8] print i, 01234
>>>range(0, 10, 1) for i in [0, 1, 2, 3, 4]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print i.
>>>range(0, 10) for i in [“smith”, “John”, “James”]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print i,
>>>range(10) for i in (0, 1, 2, 3, 4):
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print i, 01234
For i in “abcde”:
print i, abcde
16
ASTU
Cont…
How to change a list
>>>nobles = [“helium”, “neno”, “argon”, “krypton”, “xenon”]
>>>nobles[1] = “neon”
>>>nobles
[“helium”, “neon”, “argon”, “krypton”, “xenon”]

>>>nobles.append(“radon”)
>>>nobles
[“helium”, “neon”, “argon”, “krypton”, “xenon”, “radon”]
>>>len(nobles)
6

17
ASTU
Cont…
>>>nobles.insert(1, “nitrogen”)
>>>nobels
[“helium”, “nitrogen”, “neon”, “argon”, “krypton”, “xenon”,
“radon”]
>>>len(nobles)
7

18
ASTU
Cont…
>>>nobles.remove(“nitrogen”)
>>>nobles
[“helium”, “neon”, “argon”, “krypton”, “xenon”, “radon”]
>>>len(nobles)
6
or
>>>gas = nobles.pop(1)
>>>nobles
[“helium”, “neon”, “argon”, “krypton”, “xenon”, “radon”]
>>>gas
‘nitrogen’
>>>len(nobles)
6 19
ASTU
Cont…
>>>nobles.sort()
[“argon”, “helium”, “krypton”, “neon”, “radon”, “xenon”]
>>>nobles.reverse()
[“xenon”, “radon”, “neon”, “kryton”, “helium”, “argon”]

Never do the following !!


>>>list1 = nobles.sort()
>>>list1
None

20
ASTU
Cont…
Other methods for lists
lst.pop() : Remove the last element of lst and return it.
lst.index(v): Return the index of the first element of lst
which is equal to v.
lst.count(v): Count the number of elements in lst, which
is equal to v.
lst.extend(K): Append all elements in a sequence K to lst.

tuple, string, list

21
ASTU
Cont…
>>>countries
[“United States”, “China”, “Great Britain”, “Russia”, “Rep. of
Korea”, “Germany”, ”France”, “Italy”, ”Hungary”, “Australia”]
>>>golds
[46, 38, 29, 24, 13, 11, 11, 8, 8, 7] 195
>>>silvers
[ 29, 27, 17, 25, 8, 19, 11, 9, 4, 16] 165
>>>bronzes
{29, 23, 19, 32, 7, 14, 12, 11, 6, 12] 165

22
ASTU
Cont…
Built-in Functions on lists: min, max, len and sum
len returns length of a list.
sum returns the sum of the elements.
max returns the largest element.
min returns the smallest element:
>>>min(golds), max(golds), sum(golds)
(7 46 195)
>>>min(silvers), max(silvers), sum(silvers)
(4, 29, 165)
>>>min(bronzes), max(bronzes), sum(bronzes)
(6, 32, 165)

23
Traversing a list ASTU

A for loop looks at every element of a list:


for country in countries:
print(country)
We can get a range object from the rangenfunction as below: >>>
range(10)
range(0, 10)
>>> type(range(10))
<class 'range'>
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(10, 15))
[10, 11, 12, 13, 14]

24
ASTU
Cont …
If we want to modify elements, we need the index:
>>> lst = list(range(1, 11))
>>> for i in range(len(lst)):
... lst[i] = lst[i] ** 2
>>> lst
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

25
ASTU
Traversing several lists
Creating a list for total numbers of medals by nations
>>>totals = []
>>>for i in range (len(countries)):
medals= golds[i] + silvers[i] + bronzes[i]
totals.append((medals, countries[i]))
>>>print totals

[(104, 'United States'), (88, 'China'), (65, 'Great Britain'),


(81, 'Russia'), (28, 'Rep. of Korea'), (44, 'Germany'),
(34, 'France'), (28, 'Italy'), (18, 'Hungary'), (35, 'Australia')

26
Sorting ASTU

We can sort a list using its sort() method:


>>>totals.sort()
>>>totals
[(18, 'Hungary'), (28, 'Italy'), (28, 'Rep. of Korea'),
(34, 'France'), (35, 'Australia'), (44, 'Germany'), (65, 'Great
Britain'), (81, 'Russia'), (88, 'China'), (104, 'United States')]
We can reverse a list using reverse() method
>>>totals.reverse()
>>>totals
[(104, 'United States'), (88, 'China'), (81, 'Russia'), (65,
'Great Britain'), (44, 'Germany'), (35, 'Australia'), (34,
'France'), (28, 'Rep. of Korea'), (28, 'Italy'), (18, 'Hungary')]

27
ASTU
Cont…
Printing top five countries in their total numbers of
medals
>>>total[0:5]
[(104, 'United States'), (88, 'China'), (81, 'Russia'),
(65, 'Great Britain'), (44, 'Germany')

28
ASTU
Cont…
Unpacking

top_five = totals[0:5] top_five = totals[0:5]


for p in top_five: for medals, nation in top_five:
medals, nation = p print medals, nation
print medals, nation

104 United States


88 China
81 Russia
65 Great Britain
44 Germany
29
Slicing
ASTU

Slicing creates a new list with elements of the given l


ist:
sublist = mylist[i:j]
Then sublist contains elements i, i+1, . . . j-1 of mylis
t.
If i is omitted,then the sublist starts with the first element
If j is omitted, then the sublist ends with the last element
Special case: We can create a copy of a list with
list2 = list1[:]

30
ASTU
Ranking
Printing the top five countries in lexicographical ranking
table = []
for i in range(len(countries)):
table.append((golds[i], silvers[i], bronzes[i], countries[i]))

[(46, 29, 29, 'United States'), (38, 27, 23, 'China'),


(29, 17, 19, 'Great Britain'), (24, 25, 32, 'Russia'),
(13, 8, 7, 'Rep. of Korea'), (11, 19, 14, 'Germany'),
(11, 11, 12, 'France'), (8, 9, 11, 'Italy'),
(8, 4, 6, 'Hungary'), (7, 16, 12, 'Australia')]

31
ASTU
Cont…
>>>table.sort()
>>>top_five = table[-5:] What is it?
>>>top_five .reverse()
>>>for g, s, b, nation in top_five:
print g, s, b, nation

46 29 29 United States
38 27 23 China
29 17 19 Great Britain
24 25 32 Russia
13 8 7 Rep. of Korea
32
List methods ASTU

List objects Lhave the following methods:


 L.append(v) add object v at the end
 L.insert(i, v) insert element at position i
 L.pop() remove and return last element
 L.pop(i) remove and return element at position i
 L.remove(v) remove first element equal to v
 L.index(v) return index of first element equal to v
 L.count(v) return number of elements equal to v
 L.extend(K) append all elements of sequence K to L
 L.reverse() reverse the list
 L.sort() sort the list

33
ASTU
Cont…

>>> a = “banana” >>> a = [1, 2, 3]


>>> b = “banana” >>> b = [1, 2, 3]
>>> a == b >>> a == b
True equivalent True equivalent
>>>a is b >>>a is b
True identical False not identical

a “banana”
a [1, 2, 3]
b b [1, 2, 3]

34
Aliasing ASTU

An object can have more than one name. This is called aliasin
g. We have to be careful when working with mutable objects:
>>>list1 = [“A”, “B”, “C”] >>>list1 = [“A”, “B”, “C”]
>>>list 2 = List 1 >>>list2 = [“A”, “B”, “C”]
>>>list2 .append(“D”) >>>list2 .append(“D”)
>>>list2 >>>list2
[‘A’, ‘B’, ‘C’, ‘D’] [‘A’, ‘B’, ‘C’, ‘D’]
>>>list1[1] = “X” >>>list1[1] = “X”
>>>list2 >>>list2
[‘A’, ‘X’, ‘C’, ‘D’] [‘A’, ‘B’, ‘C’, ‘D’] Why?
>>>list1 is list2 >>>list1 is list2
True False
list1 [“A”, “X”, “C”]
list1 [‘A’, ‘X’, ‘C’, ‘D’]
list2 [‘A’, ‘B’, ‘C’, ‘D’]
list2

35
ASTU
Type conversion
Type conversion
tuples lists strings tuples, lists

>>>stg = “abcde” >>>tuple(stg)


>>>tpl = (“a”, “b”, “c”, “d”, “e”) (“a”, “b”, “c”, “d”, “e”)
>>>lst = [“a”, “b”, “c”, “d”, “e”] >>>list(stg)
[“a”, “b”, “c”, “d”, “e”]
>>>tuple(lst)
(“a”, “b”, “c”, “d”, “e”)
>>>list(tpl)
[“a”, “b”, “c”, “d”, “e”]

36
ASTU
SUMMARY: STRINGS, TUPLES, & LISTS

- Strings, tuples, and lists all represent sequences of


elements.

- Tuples and lists are very similar: the only difference is


their mutability, i.e., tuples are immutable while lists
are mutable.

- Strings can be conceptually regarded as a form of tuples


restricted to text data, although their representation
schemes are quite different.

37

You might also like