ISYS90088
Introduction to Application Development
Week 6 – Contd. from week 5 Nested loops; While Followed by Lists, tuples Semester 2 , 2018 Dr Antonette Mendoza
s
1
Objectives
After completing this lecture, you will be able to:
• Work with nested loops – while
• Work with lists and tuples:
– Construct lists and access items in those lists
– Use methods to manipulate lists
– Perform traversals of lists to process items in the lists – Tuples
2
Conditional Iteration: The while Loop • The while loop can be used to describe conditional
iteration
– Example: A program’s input loop that accepts values
until user enters a ‘sentinel’ that terminates the input
ISYS90088: some slides adapted from Fundamentals of Python: First 3 Programs
The Structure and Behavior of a while Loop
• Conditional iteration requires that condition be tested within loop to determine if it should continue
– Called continuation condition
– Improper use may lead to infinite loop
• while loop is also called entry-control loop
– Condition is tested at top of loop
– Statements within loop can execute zero or more times
ISYS90088: some slides adapted from Fundamentals of Python: First 4 Programs
The Structure and Behavior of a while Loop (continued)
ISYS90088: some slides adapted from Fundamentals of Python: First 5 Programs
The Structure and Behavior of a while Loop (continued)
data is the loop control variable
ISYS90088: some slides adapted from Fundamentals of Python: First 6 Programs
Count Control with a while Loop
ISYS90088: some slides adapted from Fundamentals of Python: First 7 Programs
The while True Loop and the break Statement
• while loop can be complicated to write correctly – Possible to simplify its structure and improve its
readability
ISYS90088: some slides adapted from Fundamentals of Python: First 8 Programs
The while True Loop and the break Statement (continued)
• Alternative:UseaBooleanvariabletocontrolloop
ISYS90088: some slides adapted from Fundamentals of Python: First 9 Programs
Recap: break statement
• Itterminatesthecurrentloopandresumesexecutionatthenext
statement, just like the traditional break statement in C.
• Themostcommonuseforbreakiswhensomeexternalcondition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.
• Ifyouareusingnestedloops,thebreakstatementstopsthe execution of the innermost loop and start executing the next line of code after the block.
Syntax:
>>> break
ISYS90088: some 10
slides adapted from
Fundamentals of
Introduction – lists, tuples and Dictionaries
• A list allows the programmer to manipulate a sequence of data values of any types
– Indicate by enclosing its elements in []
• A tuple resembles a list, but is immutable
– Indicate by enclosing its elements in ()
• A dictionary organizes data values by association with other data values rather than by sequential
position
Next week
• Lists and dictionaries provide powerful ways to organize data in useful and interesting applications
11
Lists
• List: Sequence of data values (items or elements)
• Some examples:
– Shopping list for the grocery store
– Guest list for a wedding
– Recipe, which is a list of instructions – Text document, which is a list of lines – Words in a dictionary
• Each item in a list has a unique index that specifies its position (from 0 to length – 1)
Fundamentals of Python: First Programs 12
List Literals and Basic Operators
• Some examples:
[‘apples’, ‘oranges’, ‘cherries’] [[5, 9], [541, 78]] – list of lists!
• When an element is an expression, its value is included in the list:
• Lists of integers can be built using range:
Fundamentals of Python: First Programs 13
List Literals & Basic Operators (cont.)
Taken from – Fundamentals of Python: First Programs 14
List Literals and Basic Operators (continued)
• len, [], +, and == work on lists as expected: >>> first = [1,2,3,4]
>>> second = list(range(1,5))
• Toprintthecontentsofalist:
• in detects the presence of an element:
Fundamentals of Python: First Programs 15
Replacing an Element in a List
• A list is mutable
– Elements can be inserted, removed, or replaced
– The list itself maintains its identity, but its state—its length and its contents—can change
• Subscript operator is used to replace an element:
– Subscript is used to reference the target of the assignment, which is not the list but an element’s position within it
Fundamentals of Python: First Programs 16
Replacing an Element in a List (continued)
• Examples: to make all words in the list uppercase
Fundamentals of Python: First Programs 17
Lists: index()
• Index : returns the index of the first element whose value is equal to the item. A ValueError exception is raised if the item is not found in the list.
• Syntax: .index(item)
Returns the first element whose value is equal to the item.
>>> n = [1,2,3,4]
>>> n.index(2)
1
Searching a List
• in determines an element’s presence or absence, but does not return position of element (if found)
• Use method index to locate an element’s position in a list
– Raises an error when the target element is not found
Try a couple on IDLE!!!!
Fundamentals of Python: First Programs 19
Example: index ()
#example to illustrate the index(). This simple program
#replaces #an item in a list once the index is known
food = [‘pizza’, ‘burger’, ‘chips’]
print(‘here are the list of items’)
print(food)
item = input(‘which item would you like to change:’)
#searching in the list for the item or value
if item not in food:
print(‘the item is not in the list’)
else:
item_index = food.index(item)
print(item_index)
#enter the new value replacing the old one
new_item = input(‘enter the new item:’)
food[item_index] = new_item
print(food)
Lists: append ()
• Append: adds items into the list one by one – one item at a time to the end of the list
• Syntax: .append(item)
Returns a list with an item
Example: append()
name_list = []
again = ‘y’
#add names into the list – adds it to the end of list
while again == ‘y’:
name = input(‘enter the name:’)
name_list.append(name)
#to add another name into the list
print(‘do you want to add more name’)
again = input(‘y = yes, anything else = no:’)
#display the names that were added
print(‘here are the names:’)
print(name)
Aliasing and Side Effects
• Mutable property of lists leads to interesting phenomena:
first and second are aliases (refer to the exact same list object)
Fundamentals of Python: First Programs 23
Aliasing and Side Effects (continued) • To prevent aliasing, copy contents of object:
Alternative:
Fundamentals of Python: First Programs
24
Equality: Object Identity and Structural Equivalence
Values are the same but they are different lists
(VS)
the lists are the same => first and second- they are alias
Fundamentals of Python: First Programs
25
Sorting a List
• A list’s elements are always ordered by position, but you can impose a natural ordering on them
– For example, in alphabetical order or ascending order • When the elements can be related by comparing them
<, >, and ==, they can be sorted
– The method sort mutates a list by arranging its elements in ascending order
Fundamentals of Python: First Programs 26
Lists: sort()
• sort: it simply rearranges elements in a list so they appear to be ascending order.
• Syntax: .sort()
Returns the list sorted
Lists: sort()
>>> name = [‘anne’, ‘david’, ‘james’, ‘cathy’,
‘bob’]
>>> name.sort()
>>> name
[‘anne’, ‘bob’, ‘cathy’, ‘david’, ‘james’]
>>> list1 = [3,2, 1, 1, 2, 4, 54, 45]
>>> list1.sort()
>>> list1
[1, 1, 2, 2, 3, 4, 45, 54]
>>>
Example: Using a List to Find the Median of a Set
of Numbers
#median of numbers in a list. Assume the input is a text – integers
listofnumbers = input (‘enter a list of numbers:’)
numbers = []
words = listofnumbers.split()
for word in words:
numbers.append(float(word))
print(numbers)
#sort the list and print the median or its midpoint
#numbers.sort() or use it this way numbers = sorted(numbers)
numbers.sort()
print(numbers)
midpoint = len(numbers) // 2
print(“the median is”, end=” “)
if len(numbers) % 2 == 1:
print(numbers[midpoint])
else:
print((numbers[midpoint] + numbers[midpoint -1]) /2)
29
Lists: insert ()
• Insert : insert an item into the item at a specific position. Two arguments are provided to this method: the index specifying where the item should be inserted and; the item that you want to insert.
• Syntax: .insert(
• Returns a list with the item added.
Example: insert ()
>>> list1 = [‘cat’, ‘dog’, ‘horse’]
>>> list1.insert(3, ‘bird’)
>>> list1
[‘cat’, ‘dog’, ‘horse’, ‘bird’]
>>> list1 = [‘cat’, ‘dog’, ‘horse’]
>>> list1.insert(3, ‘bird’)
>>> list1
[‘cat’, ‘dog’, ‘horse’, ‘bird’]
>>> name = [‘anne’, ‘david’]
>>> name.insert(0, ‘anto’)
>>> name
>>> name.insert(4, ‘3’)
>>> name
[‘anto’, ‘anne’, ‘david’, ‘3’]
>>> name.insert(4, 1)
>>> name
[‘anto’, ‘anne’, ‘david’, ‘3’, 1]
>>>
Lists: reverse()
• reverse:itsimplyreversestheorderoftheitemsinthe list.
• Syntax: .reverse()
Returns the list reversed.
• Example: >> name
[‘ant’, ‘bee’, ‘cat’, ‘dog’, ‘elephant’]
>>> name.reverse()
>>> name
[‘elephant’, ‘dog’, ‘cat’, ‘bee’, ‘ant’]
>>>
Lists: remove()
• remove : removes an item from the list. You pass an item as an argument and the first element containing that item is removed.
• This reduces the size of the list one by one
• All of the elements after the removed element are
shifted one position towards the beginning of the list
• Syntax: .remove(item)
Returns a list with one less item .
Example: remove()
# example to illustrate the remove().
food = [‘pizza’, ‘burger’, ‘chips’]
print(food)
item = input(‘which item would you like to
remove:’)
if item not in food:
print(‘the item is not in the list’)
else:
food.remove(item)
print(‘here is the new list:’)
print(food)
Lists: del()
• del:somesituationsrequirethatyouhavetoremovean element from a specific index in the list regardless of what item is actually stored in that index.
• Syntax:
del
Returns a list with one less item .
• Example:
>>> name = [‘anne’, ‘david’, ‘james’] >>> del name[2]
>>> name
[‘anne’, ‘david’]
>>>
Examples: reversing and sorting a List in loops
# example to reverse a list of items in loops
listofvalues =[10,15,20,40]
for i in reversed(listofvalues):
print (i)
# example to sort a list of items listofvalues =[10,25,20,40, 11] for i in sorted(listofvalues):
print (i)
# another way of using sort – example listofvalues.sort()
for i in listofvalues:
print(i)
36
Lists: max() and min() functions
max: takes in a list as an argument and returns the max value in that list.
min: takes in a list and returns the min value in that list
Syntax:
min()
max()
Examples:
>>> list1 = [3,2, 1, 1, 2, 4, 54, 45]
>>> max(list1)
54
>>> min(list1)
1
37
BREAK!
Fundamentals of Python: From First Programs Through Data Structures 38
Lists: two-dimensional
A 2-dimensional list is a list that has others lists as its elements
Examples:
>>> students = [[‘joe’,’jack’, ‘mary’],
[‘sam’, ‘jane’]]
>>> students
[[‘joe’, ‘jack’, ‘mary’], [‘sam’, ‘jane’]]
>>> students[0]
Joe
>>>student[0][1]
‘jack’
39
Lists: two-dimensional
Useful when working with multiple lists. Example: write a program that calculates the grade-average for a teacher. Lets say we have 2 students each of who do three assessments. How can we represent and work with the lists?
Ass 1
Ass2
mid-sem test
10
15
8
5
10
6
40
Lists: two-dimensional
>>>Scores = [[10,15,8], [5,10,6]]
>>>scores[0][0]
10
Ass 1
Ass2
mid-sem test
10
15
8
5
10
6
41
Lists: two-dimensional – work on this program at home!!!
• Program to multiply two matrices using nested loops # add two 2×2 matrix
X = [[1,2], [2,1],[1,3]]
Y = [[4,1], [2,1], [2,2]]
result = [[0,0],[0,0],[0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
42
Tuples
• A tuple resembles a list, but is immutable – Indicate by enclosing its elements in ()
• Thedifferencesbetweentuplesandlistsare:
– the tuples cannot be changed unlike lists
– tuples use parentheses, whereas lists use square brackets
• Creating a tuple is as simple as putting different comma- separated values.
43
Tuples
• Lists can be converted to tuples; two sets of tuples can be concatenated
• For example:
• Most of the operators and functions used with lists
can be used in a similar fashion with tuples
Fundamentals of Python: First Programs 44
Tuples
• Most of the operators and functions used with lists can be used in a similar fashion with tuples:
– The empty tuple is written as two parentheses containing nothing
tup1 = ();
– To write a tuple containing a single value you have to include a comma, even though there is only one value −
tup1 = (50,);
45
Tuples
• Most of the operators and functions used with lists can be used in a similar fashion with tuples:
– The empty tuple is written as two parentheses containing nothing
tup1 = ();
for lists: list1 = []
– To write a tuple containing a single value you have to include
a comma, even though there is only one value − tup1 = (50,);
For lists: list1 = [50]
46
Tuples
• Likestringindices,tupleindicesstartat0.Theoperations performed are: concatenation, iteration, in, slicing and indexing
• AccessingValuesinTuples:usethesquarebracketsforslicing along with the index or indices to obtain value available at that index.
• UpdatingTuples-Tuplesareimmutablewhichmeansyou cannot update or change the values of tuple elements.
• DeleteTupleElements-Removingindividualtupleelementsis not possible.
47
Tuples
Ø To explicitly remove an entire tuple, just use the del statement. For example:
tuple1 = (‘physics’, ‘chemistry’, 1997, 2000)
print (tuple1)
del tuple1
print (“After deleting tuple : “)
print (tuple1)
• Thisproducesthefollowingresult(checkexample).Notean exception raised, this is because after del tup tuple does not exist any more.
Example:
>>>tuple3 = (1,2,3)
>>>list(tuple3) 48 [1,2,3]
Tuples
Built-in Tuple Functions can be used: ## length, max and min in a tuple
tuple1, tuple2 = (‘zar’, ‘xyz’, ‘zara’), (100, 500, 20)
print (“Max value element : “, max(tuple1))
print (“Max value element : “, max(tuple2))
print (“Min value element : “, min(tuple1))
print (“Min value element : “, min(tuple2))
print (“First tuple length : “, len(tuple1))
print (“Second tuple length : “, len(tuple2))
#convert a list of items into tuples
Listofitems = [23, ‘years’, ‘dogs’, ‘cats’];
toaTuple = tuple(Listofitems)
print (“Tuple elements : “, toaTuple)
49
Difference between lists and tuples
• Lists are mutable. Lists however have this method called append. In order for most of your appends to be fast, python will actually create a larger array in memory just in case you append.
• This way, when you do append, it does not have to recreate a list every time. You can add items to the list .How would it know that you don’t want to maybe add a 4th 5th 6th element? To play safe, we assume you might want more in the memory
• On the other hand, by using tuples, it tells python that you want an immutable structure. Give me space for 3 things, fill those slots up, and move on.
• Sincetuplesareimmutable,thismeansthattuplesarefixed.Wecan’tdo anything to them in memory.
• Performance:processingoftuplesissaidtobefasterthanlistprocessing
• Usingtuplesissafe:Sincetheyareimmutable,wecantchangecontentof the tuple. This can be useful when you don’t want any data modified by your code
50