Download presentation
Presentation is loading. Please wait.
1
Advanced Computer Programming
Sinan AYDIN Lists, Tuples and Dictionaries
2
Lists, Tuples and Dictionaries
Sequence Lists Tuples Unpacking and Slicing Dictionary Methods
3
Sequence Lists, Tuples and Dictionaries A sequence is a series of contiguous values that often are related. Python strings are sequences, as is the value returned by function range a Python built-in function that returns a list of integers. To create an empty list : aList = [] To create a list that contains a sequence of values: aList = [ 1, 2, 3 ] To create an empty tuple: aTuple = () To create a tuple that contains a sequence of values: aTuple = 1, 2, 3 or (1,2,3) When creating a one-element tuple called a singleton aSingleton = 1,
4
Using Lists Lists, Tuples and Dictionaries Although lists are not restricted to homogeneous data types (i.e., values of the same data type), Python programmers typically use lists to store sequences of homogeneous values. In general, a program uses a list to store homogeneous values for the purpose of looping over these values and performing the same operation on each value. # Fig. 5.3: fig05_03.py # Creating, accessing and changing a list. aList = [] # create empty list # add values to list for number in range( 1, 11 ): aList += [ number ] print ("The va(lue of aList is:", aList) # access list values by iteration print ("\nAccessing values by iteration:") for item in aList: print ( item) print() # access list values by index print ("\nAccessing values by index:") print ("Subscript Value") for i in range( len( aList )): print ("%9d %7d" % ( i, aList[ i ])) # modify list print ("\n Modifying a list value...") print ("Value of aList before modification:", aList) aList[ 0 ] = -100 aList[ -3 ] = 19 print ("Value of aList after modification:", aList) Accessing values by iteration: Accessing values by index: Subscript Value Modifying a list value... Value of aList before modification: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Value of aList after modification: [-100, 2, 3, 4, 5, 6, 7, 19, 9, 10]
5
Using Lists Lists, Tuples and Dictionaries Enter 10 integers: Enter integer 1: 10 Enter integer 2: 8 Enter integer 3: 6 Enter integer 4: 4 Enter integer 5: 2 Enter integer 6: 9 Enter integer 7: 7 Enter integer 8: 5 Enter integer 9: 3 Enter integer 10: 1 Creating a histogram from values: Element Value Histogram ********** ******** ****** **** ** ********* ******* ***** *** * values = [] # a list of values # input 10 values from user print ("Enter 10 integers:") for i in range( 10 ): newValue = int( input( "Enter integer %d: " % ( i + 1 ) ) ) values += [ newValue ] print ("\nCreating a histogram from values:") print ("%s %10s %10s" % ( "Element", "Value", "Histogram" )) for i in range( len( values ) ): print ("%7d %10d %s" % ( i, values[ i ], "*" * values[ i ] )) Obtain odd and prime numbers as a List for numbers 1 to 100
6
Using Lists Lists, Tuples and Dictionaries Obtain odd and prime numbers as a List for numbers 1 to 100 def prime(x): if (x==1): return False elif (x==2): return True else: for i in range(2,x): if (x % i == 0): return False return True def odd(x): if x%2==1: return True return False result=[] for i in range(1,100): if prime(i) and odd(i): result+=[i] print(result)
7
Using Tuples Lists, Tuples and Dictionaries Whereas lists typically store sequences of homogeneous data, tuples typically store sequences of heterogeneous data this is a convention, not a rule, that Python programmers follow. hour = int( input( "Enter hour: " ) ) minute = int( input( "Enter minute: " ) ) second = int( input( "Enter second: " ) ) currentTime = hour, minute, second # create tuple print ("The value of currentTime is:", currentTime) # access tuple print ("The number of seconds since midnight is", ( currentTime[ 0 ] * currentTime[ 1 ] * 60 +currentTime[ 2 ] )) Enter hour: 10 Enter minute: 10 Enter second: 10 The value of currentTime is: (10, 10, 10) The number of seconds since midnight is 36610 currentTime[ 0 ] = 0 TypeError: 'tuple' object does not support item assignment
8
Mutable, immutable Lists, Tuples and Dictionaries Note that the use of lists and tuples is not a rule, but rather a convention that Python programmers follow. Python does not limit the data type stored in lists and tuples (i.e., they can contain homogeneous or heterogeneous data). The primary difference between lists and tuples is that lists are mutable whereas tuples are immutable. l1=[1, 'two', 3] l2=["bir", 2, "uc"] l3=[[1, 'two', 3],["bir", 2, "uc"]] l4=[l1,l2] print (l1) print (l2) print (l3) print (l4) print (l3==l4) print (id(l3)==(l4)) l1.append("four") print (l4)
9
Sequence Unpacking Unpacking string... String values: a b c
Lists, Tuples and Dictionaries Unpacking string... String values: a b c Unpacking list... List values: 1 2 3 Unpacking tuple... Tuple values: a A 1 Before swapping: x = 3, y = 4 After swapping: x = 4, y = 3 aString = "abc" aList = [ 1, 2, 3 ] aTuple = "a", "A", 1 print ("Unpacking string...") first, second, third = aString print ("String values:", first, second, third) print ("Unpacking list...") first, second, third = aList print ("List values:", first, second, third) print ("Unpacking tuple...") first, second, third = aTuple print ("Tuple values:", first, second, third) # swapping two values x = 3 y = 4 print ("Before swapping: x = %d, y = %d" % ( x, y )) x, y = y, x # swap variables print ("After swapping: x = %d, y = %d" % ( x, y ))
10
Sequence Slicing Lists, Tuples and Dictionaries sliceString = "abcdefghij" sliceTuple = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ) sliceList = [ "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X" ] print(sliceString[0: 2 ]) print(sliceTuple[5:len(sliceTuple)]) print( sliceList[2:]) print(sliceString[-4: -1 ]) print(sliceString[-1 ]) print(sliceTuple[-2:-1]) print( sliceList[-5:-1]) ab (6, 7, 8, 9, 10) ['III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'] ghi j (9,) ['VI', 'VII', 'VIII', 'IX']
11
Dictionaries Lists, Tuples and Dictionaries In addition to lists and tuples, Python supports another powerful data type, called the dictionary. Dictionaries (called hashes or associative arrays in other languages) are mapping constructs consisting of key-value pairs. emptyDictionary = {} #Each key-value pair is of the form key : value dictionary = { 1 : "one", 2 : "two" } grades = {"John": 87, "Steve": 76, "Laura": 92, "Edwin": 89} print ("\nAll grades:", grades) print ("\nSteve's current grade:", grades[ "Steve" ]) grades[ "Steve" ] = 90 print ("Steve's new grade:", grades[ "Steve" ]) grades[ "Michael" ] = 93 print ("\nDictionary grades after modification:") print (grades) del grades[ "John" ] print ("\nDictionary grades after deletion:") print (grades)
12
List Methods Lists, Tuples and Dictionaries
13
List and Dictionary Methods
Lists, Tuples and Dictionaries --Mylist-- [1, 2, 3, 4, 5, 2, 4, 6, 8] --Mylist.append(2)-- [1, 2, 3, 4, 5, 2, 4, 6, 8, 2] --Mylist.count(2)-- 3 --Mylist.extend([10,11,12])-- [1, 2, 3, 4, 5, 2, 4, 6, 8, 2, 10, 11, 12] --print(Mylist.index(2))-- 1 --Mylist.insert(3,99)-- [1, 2, 3, 99, 4, 5, 2, 4, 6, 8, 2, 10, 11, 12] --Mylist.pop()-- [1, 2, 3, 99, 4, 5, 2, 4, 6, 8, 2, 10, 11] --Mylist.pop(0)-- [2, 3, 99, 4, 5, 2, 4, 6, 8, 2, 10, 11] --Mylist.remove(2)-- [3, 99, 4, 5, 2, 4, 6, 8, 2, 10, 11] --Mylist.reverse()-- [11, 10, 2, 8, 6, 4, 2, 5, 4, 99, 3] --Mylist.sort()-- [2, 2, 3, 4, 4, 5, 6, 8, 10, 11, 99]
14
Dictionary Methods Lists, Tuples and Dictionaries
15
Dictionary Methods Lists, Tuples and Dictionaries
# Fig. 5.13: fig05_13.py # Dictionary methods. mD = {1: "January", 2: "February", 3: "March",4: "April", 5: "May", 6: "June", 7: "July",8: "August", 9: "September", 10: "October",11: "November", 12: "December"} print(mD) print ("The dictionary items are:(mD.items())") print(mD.items()) print("\nThe dictionary keys are:(mD.keys())") print (mD.keys()) print ("\nThe dictionary values are:(print (mD.values()))") print (mD.values()) print ("\nUsing a for loop to get dictionary items:") for key in mD.keys(): print ( "mD[", key, "] =", mD[key]) print ("--print(mD.get(2))---") print(mD.get(2)) print ("--mD.popitem(5)---") mD.popitem() print(mD.items())
16
Dictionary Methods Lists, Tuples and Dictionaries
# Fig. 5.13: fig05_13.py # Dictionary methods. mD = {1: "January", 2: "February", 3: "March",4: "April", 5: "May", 6: "June", 7: "July",8: "August", 9: "September", 10: "October",11: "November", 12: "December"} print(mD) print ("The dictionary items are:(mD.items())") print(mD.items()) print("\nThe dictionary keys are:(mD.keys())") print (mD.keys()) print ("\nThe dictionary values are:(print (mD.values()))") print (mD.values()) print ("\nUsing a for loop to get dictionary items:") for key in mD.keys(): print ( "mD[", key, "] =", mD[key]) print ("--print(mD.get(2))---") print(mD.get(2)) print ("--mD.popitem()---") mD.popitem() print(mD.items()) {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'} The dictionary items are:(mD.items()) dict_items([(1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December')]) The dictionary keys are:(mD.keys()) dict_keys([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) The dictionary values are:(print (mD.values())) dict_values(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']) Using a for loop to get dictionary items: mD[ 1 ] = January mD[ 2 ] = February mD[ 3 ] = March mD[ 4 ] = April mD[ 5 ] = May mD[ 6 ] = June mD[ 7 ] = July mD[ 8 ] = August mD[ 9 ] = September mD[ 10 ] = October mD[ 11 ] = November mD[ 12 ] = December --print(mD.get(2))--- February --mD.popitem(5)--- dict_items([(1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November')])
17
Passing Lists to Functions
Lists, Tuples and Dictionaries def modifyList( bList ): for i in range( len( bList ) ): bList[ i ] *= 2 def modifyElement( element ): element *= 2 aList = [ 1, 2, 3, 4, 5 ] print ("Effects of passing entire list:") print ("The values of the original list are:") print(aList) modifyList( aList ) print ("\nThe values of the modified list are:") print ( aList) print ("\nEffects of passing list element:") print ("aList[ 3 ] before modifyElement:", aList[ 3 ]) modifyElement( aList[ 3 ] ) print ("aList[ 3 ] after modifyElement:", aList[ 3 ]) print ("\nEffects of passing slices of list:") print ("aList[ 2:4 ] before modifyList:", aList[ 2:4 ]) modifyList( aList[ 2:4 ] ) print ("aList[ 2:4 ] after modifyList:", aList[ 2:4 ])
18
Passing Lists to Functions
Lists, Tuples and Dictionaries def modifyList( bList ): for i in range( len( bList ) ): bList[ i ] *= 2 def modifyElement( element ): element *= 2 aList = [ 1, 2, 3, 4, 5 ] print ("Effects of passing entire list:") print ("The values of the original list are:") print(aList) modifyList( aList ) print ("\nThe values of the modified list are:") print ( aList) print ("\nEffects of passing list element:") print ("aList[ 3 ] before modifyElement:", aList[ 3 ]) modifyElement( aList[ 3 ] ) print ("aList[ 3 ] after modifyElement:", aList[ 3 ]) print ("\nEffects of passing slices of list:") print ("aList[ 2:4 ] before modifyList:", aList[ 2:4 ]) modifyList( aList[ 2:4 ] ) print ("aList[ 2:4 ] after modifyList:", aList[ 2:4 ]) Effects of passing entire list: The values of the original list are: [1, 2, 3, 4, 5] The values of the modified list are: [2, 4, 6, 8, 10] Effects of passing list element: aList[ 3 ] before modifyElement: 8 aList[ 3 ] after modifyElement: 8 Effects of passing slices of list: aList[ 2:4 ] before modifyList: [6, 8] aList[ 2:4 ] after modifyList: [6, 8]
19
Sorting and Searching Lists
Lists, Tuples and Dictionaries # Fig. 5.17: fig05_17.py # Sorting a list. aList = [2, 6, 4, 8, 10, 12, 89, 68, 45, 37] print ("Data items in original order") print (aList) aList.sort() print("\n\nData items after sorting") print (aList) Data items in original order [2, 6, 4, 8, 10, 12, 89, 68, 45, 37] Data items after sorting [2, 4, 6, 8, 10, 12, 37, 45, 68, 89] aList = range( 0, 199, 2 ) searchKey = int( input( "Enter integer search key: " ) ) if searchKey in aList: print ("Found at index:", aList.index( searchKey )) else: print ("Value not found")
20
Multiple-Subscripted Sequences
Lists, Tuples and Dictionaries b = [ [ 1, 2 ], [ 3, 4 ] ] c = ( ( 1, 2 ), ( 3, 4, 5 ) ) from random import * Matrix = [[randint(1, 100) for j in range(0, 10)] for i in range(0, 10)] for x in range(len(Matrix)): print(Matrix[x])
21
Advanced Computer Programming
Sinan AYDIN Lists, Tuples and Dictionaries
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.