chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · values vs types • we have...

31
1 Chapter 9 List Slides sold at copy shop ITS100: Introduction to Computer and Programming 1

Upload: others

Post on 03-Jun-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

1

Chapter 9List

Slides sold at copy shop

ITS100: Introduction to Computer and Programming1

Page 2: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Topics

1. Values and Types2. Lists and List type3. Operations on lists4. Lists in use and Problem solving

variables

statements

functions

data

2

Page 3: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Values vs Types

• We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

• They are data values (or values, for short) and they belong to different datatypes (or types)

• 4à typeint• 4.0à typefloat• True,Falseà typebool• “hello”,“world”à typestr

>>>type(4)<class'int'>>>>type(4.0)<class'float'>>>>type(True)<class'bool'>>>>type("hello")<class'str'>>>>

3

Page 4: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Atomic vs Composite

• We often differentiate between atomic values and composite values

• Anatomicvaluecannotbreakdownintosmallervalues(rememberatomsinPhysic?)

• Acompositevaluecanbebrokendownintosmaller/constituentvalues(inPhysic,amoleculecanbebrokendownintoothermoleculesoratoms?)

• E.g. numbers (4, 4.0) are atomic• Bool values (True/False) are also atomic

4

Page 5: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Atomic vs Composite

• But strings (“hello”, “world”) are not atomic, since a string is a sequence of characters (i.e. a string consisting of only one character)

• “hello”à “h”,“e”,“l”,“l”,“o”• We can access (read) such characters by

for c in "hello":print(c)

Program

Outputofprogram

hello

5

Page 6: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Other access methods

• Indexing (access one character)

• Slicing (access multiple characters)

for i in range(0, 5):print("hello"[i])

print("hello"[0:1])print("hello"[0:2])print("hello"[0:5])

Output

hhehello

Output

hello

6

Page 7: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Why composite values?

• It is good to be able to group simple values into a composite value and process it as a bunch.

• Forexample:wecangroupfirstnameandsurnameintofullname• Firstname:“hung”• Surname:“nguyen duy”• Fullname:“hungnguyen duy”

• Using strings, we can group values that are strings themselves like the above example.

7

Page 8: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Lists and List type

• But we can not group values that are not strings• Forexample:wecannotgroupfullname(string)withage(int)

• Fullname:“hungnguyen duy”• Age:18• “hungnguyen duy”18isnotalegalvalue

• List addresses this issue

• Basically, lists are composite values; and list type is a composite type

hungbib = ["hung nguyen duy", 18]print("hung's full name:", hungbib[0])print("hung's age:", hungbib[1])

Output

hungnguyen duy18

8

Page 9: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Lists and List type

• A list can consist of values of any types, e.g. we can have

• Alistofnumbers• Alistofstrings• Alistofnumbersandstrings• Alistoflists

lofnum = [18,1998]lofstr = ["hung", "nguyen duy"]lofnumAndstr = ["hung", "nguyen duy", 18, 1998]lofl = [["hung", "nguyen duy"], [18, 1998]]

9

Page 10: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

The power of lists

• Using lists, we can write some programs we can not write by using only atomic values

• Example: Write a program to get (unknown) positive numbers from a user. If user inputs “-1”, then display all inputted numbers in an increasing order

10

Page 11: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

A failed attempt

# reserve some variables to store user’s numbersx1 = -1x2 = -1# xi = -1xn = -1

# read i = 0cont= Truewhile cont:

x = float(input("input a number"))if x==-1:

cont = Falseelse:

i = i +1xi = x

# sort

# display

11

Page 12: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Solution

lonum = []# readcont= Truewhile cont:

x = float(input("input a number"))if x==-1:

cont = Falseelse:

lonum.append(x) # add x to the end# sortlonum.sort()# displayprint(lonum)

12

Page 13: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

List operations • Create

• lon =[1,3,2]• Access

• Indexing:lon[0],lon[1]• Slicing:lon[0:1],lon[0:2]

• Update• lon[0]=4

• Delete• dellon[1]• lon.remove(1)• lon.clear()

• Add to the end• lon.append(4)

• Concatenate• lon +[“hello”,“world”]

• Check memberships• xinlon

• Find length• len(lon)

• Sort• lon.sort()

• Find biggest, smallest• max(lon)• min(lon)

• etc

13

Page 14: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Create

• Use [ , ]• Examples:

• Elements of a list can be pretty much anything (values, variables, and even functions)

lofnum = [18,1998]lofstr = ["hung", "nguyen duy"]lofnumAndstr = ["hung", "nguyen duy", 18, 1998]lofl = [["hung", "nguyen duy"], [18, 1998]]

lofnum = [18,1998]lofstr = ["hung", "nguyen duy"]lofl = [lofnum,lofstr]lofunc = [print, sum]lofunc[0](lofunc[1](lofnum))

Output

2016 14

Page 15: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Access

• Indexing: aList[anIndex]• Examples in the book (p 112)

A = ["Supperman", "Batman", "Spiderman",\"Snoopy", "Peterpan"]print(A[0])print(A[2])

Output

SupermanSpiderman

A = ["Supperman", "Batman", "Spiderman",\"Snoopy", "Peterpan"]print(A[-1])print(A[-2])

Output

PeterpanSnoopy

15

Page 16: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

How a list is indexed?

"Supperman" "Batman" "Spiderman" "Snoopy" "Peterpan"

0 1 2 3 4

-5 -4 -3 -2 -1

A[0] = A[0-len(A)]A[1] = A[1-len(A)]..................A[len(A)-1] = A[len(A)-1–len(A)]

16

Page 17: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Access

• Slicing: aList[start:stop]

A = ["Supperman", "Batman", "Spiderman",\"Snoopy", "Peterpan"]print(A[1:4])print(A[0:1])

Output

['Batman','Spiderman','Snoopy']['Supperman']

A = ["Supperman", "Batman", "Spiderman",\"Snoopy", "Peterpan"]print(A[-3:-1])

Output

['Spiderman','Snoopy']

A = ["Supperman", "Batman", "Spiderman",\"Snoopy", "Peterpan"]print(A[:1]) # short for A[0:1]print(A[1:]) # short for A[1:5]print(A[:]) # short for A[0:5] 17

Page 18: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Access a list in a list

"Supperman" "Batman" "Snoopy" "Peterpan"

0 1 2 3 4

0 1

”Spider" ”man"

A = ["Supperman", "Batman", ["Spider", "man"],\"Snoopy", "Peterpan"]print(A[2][0])print(A[2][1])

Output

Spiderman

18

Page 19: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Update

• Use assignment: aList[anIndex] = ....• Examples in the book (p 114)

E = [10,20,30]E[1] = 500print(E)

Output

[10,500,30]

E = [10,20,30]E[3] = 500print(E)

Errormessage

IndexError:listassignmentindexoutofrange

E = [10,20,30]E[1] = [1,2,3]print(E)

Output

[10,[1,2,3],30] 19

Page 20: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Delete elements

• del aList[anIndex] removes one element

• aList.remove(value) removes the first element whose value = value

• aList.clear() removes all elements

E = [10,20,30]del E[1]print(E)

Output

[10,30]

E = [10,20,30,20]E.remove(20)print(E)

Output

[10,30,20]

E = [10,20,30,20]E.clear()print(E)

20

Page 21: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Add to the end

• aList.append(value)E = [10,20,30]E.append(500)print(E)

Output

[10,20,30,500]

E = [10,20,30]for i in range(5):

E.append(i)print(E)

Output

[10,20,30,0,1,2,3,4]

21

Page 22: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Other operations

• Concatenation: aList1 + aList2

• Check membership

E = [10,20,30]x=0print([x+1]+ E)

Output

[1,10,20,30]

E = [10,20,30]x=0if x in E:

print("x is in E")else:

print("x is not in E")

22

Page 23: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Other operations

• Iteration

• List comprehension (not in textbook, but I see in lab)

E = [10,20,30]for x in E:

print(x+1)

Output

112131

E = [10,20,30]N = []for x in E:

N.append(x+1)print(N)

Output

[11,21,31]

E = [10,20,30]N = [x+1 for x in E]print(N)

Output

[11,21,31]23

Page 24: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

And more (see p 118)

• sum(aList)• sum([1,2,3])à 1+2+3

• len• len([1,2,3])à 3

• max• max([1,2,3])à 3

• min• min([1,2,3])à 1

• count• [1,2,3,1].count(1)à 2

• index• [1,2,3,1].index(1)à 0

• insert

• pop

• reverse, sort, ...

E = [10,20,30]E.insert(1,40)print(E) #[10, 40,20,30]

E = [10,20,30]x = E.pop() # x = 30, E = [10, 20]

24

Page 25: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Kinds of list operations• As we have seen, sometimes we write aList.op(...), e.g.

• [1,2,3,1].count(1)• [1,2,3,1].index(1)• E.insert(1,40)

• But we also write op(aList), e.g.• sum([1,2,3])• len([1,2,3])• max([1,2,3])

• Operations of the first kind are called methods• Operations of the second kind are called functions• In this course we do not study the difference between

functions and methods. All you need to remember is the ways to use/call them.

25

Page 26: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Lists in use

Problem: Write a program to get a string from user, and check if it is “Cat”, “Rat” or “Bat”A = ["Cat", "Rat", "Bat"]x = input("Which animal u want to see?")if x in A:

print("We have !")else:

print("We do not have")

26

Page 27: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Lists in use

Problem: Write a function mysum(lon) to compute the sum of a given list of numbers# listOfnumber -> number# Ex: [1,2] -> 3 ; [1] -> 1; [] -> 0def mysum(lon):

s = 0for x in lon:

s = s + xreturn s

def mysum2(lon):s = 0for i in range(0, len(lon)):

s = s + lon[i]return s

27

Page 28: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Problem solving (p 122)

Problem A: Write a program to get names from user (repeat until user input “x”) then display the names in alphabetical ordercont= Truelon = []while cont:

name= input("Give me a name")if name == "x":

cont = Falseelse:

lon.append(name)lon.sort()print(lon)

Output

GivemeanamehungGivemeanameaaGivemeanamebbGivemeanamex['aa','bb','hung']>>>

28

Page 29: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Problem solving (p 122)

Problem B: Write a program to get many numbers from user (repeat until user inputs “-1”) then display only the numbers that are more than the average

29

Page 30: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

Problem solvingFull name Number grade Lettergrade

Nguyenduy Hung 20 D

Bunyarit Uyyanonvara 15 F

.... .... ....

Full name Number grade Lettergrade

Nguyenduy Hung 10 F

Bunyarit Uyyanonvara 35 C

Smart 100 A

... ... ...

ITS100

ITS101

When a semester ends, instructors submit grades to the registry. Write a program to help the registry to calculate GPA of each student in that semester. 30

Page 31: chapter 9- listict.siit.tu.ac.th/~hung/its100/chapter-9-list.pdf · Values vs Types • We have written programs using such entities as 4, 4.0; True, False; “hello”, “world”

its100 = [["nguyen duy hung", 20, "D"], ["Bunyarit Uyyanonvara", 15, "F"]]

its101 = [["Bunyarit Uyyanonvara", 35, "C"], ["nguyen duy hung", 10, "F"], ["Smart", 100, "A"]]

its102 = [["nguyen duy hung", 100, "A"], ["Smart", 90, "A"]]

31