1 / 21

Sinan AYDIN

Advanced Computer Programming. Sinan AYDIN. Lists, Tuples and Dictionaries. Lists, Tuples and Dictionaries. Lists, Tuples and Dictionaries. Sequence Lists Tuples Unpacking and Slicing Dictionary Methods. Sequence. Lists, Tuples and Dictionaries.

delsier
Download Presentation

Sinan AYDIN

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced Computer Programming Sinan AYDIN Lists, Tuples and Dictionaries

  2. Lists, Tuples and Dictionaries Lists, Tuples and Dictionaries • Sequence • Lists • Tuples • UnpackingandSlicing • 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 returnedby function rangea 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 tuplecalled a singletonaSingleton = 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 storehomogeneous values for the purpose of looping over these values and performing the sameoperation on each value. # Fig. 5.3: fig05_03.py# Creating, accessingandchanging a list.aList = [] # createemptylist# addvaluestolistfornumberin range( 1, 11 ):aList += [ number ]print("Theva(lue of aList is:", aList)# accesslistvaluesbyiterationprint("\nAccessingvaluesbyiteration:")foritemin aList:print( item)print()# accesslistvaluesbyindexprint("\nAccessingvaluesbyindex:")print("Subscript Value")fori in range( len( aList )):print("%9d %7d" % ( i, aList[ i ]))# modifylistprint("\nModifying a listvalue...")print("Value of aListbeforemodification:", aList)aList[ 0 ] = -100aList[ -3 ] = 19print("Value of aListaftermodification:", aList) Accessing values by iteration: 12345678910 Accessing values by index: Subscript Value 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 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: Enterinteger 1: 10 Enterinteger 2: 8 Enterinteger 3: 6 Enterinteger 4: 4 Enterinteger 5: 2 Enterinteger 6: 9 Enterinteger 7: 7 Enterinteger 8: 5 Enterinteger 9: 3 Enterinteger 10: 1 Creating a histogramfromvalues: Element Value Histogram 0 10 ********** 1 8 ******** 2 6 ****** 3 4 **** 4 2 ** 5 9 ********* 6 7 ******* 7 5 ***** 8 3 *** 9 1 * values = [] # a list of values# input 10 valuesfromuserprint("Enter 10 integers:")fori in range( 10 ):newValue = int( input( "Enterinteger %d: " % ( i + 1 ) ) )values += [ newValue ]print("\nCreating a histogramfromvalues:")print("%s %10s %10s" % ( "Element", "Value", "Histogram" ))fori 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 Truedef odd(x):if x%2==1:return True return Falseresult=[]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 datathis is a convention, not a rule, that Python programmersfollow. hour = int( input( "Enterhour: " ) )minute = int( input( "Enterminute: " ) )second = int( input( "Entersecond: " ) )currentTime = hour, minute, second# createtupleprint("Thevalue of currentTime is:", currentTime)# accesstupleprint("Thenumber of seconds since midnight is", ( currentTime[ 0 ] * 3600 + 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 nota rule, but rather a convention that Python programmers follow. Python does not limit thedata type stored in lists and tuples (i.e., they can contain homogeneous or heterogeneousdata). The primary difference between lists and tuples is that lists are mutable whereastuples 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 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", 1print("Unpackingstring...")first, second, third = aStringprint("Stringvalues:", first, second, third)print("Unpackinglist...")first, second, third = aListprint("Listvalues:", first, second, third)print("Unpackingtuple...")first, second, third = aTupleprint("Tuplevalues:", first, second, third)# swappingtwovaluesx = 3y = 4print("Beforeswapping: x = %d, y = %d" % ( x, y ))x, y = y, x # swap variablesprint("Afterswapping: 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 mappingconstructs consisting of key-value pairs. emptyDictionary = {}#Eachkey-valuepair is of the form key : valuedictionary = { 1 : "one", 2 : "two" }grades = {"John": 87, "Steve": 76, "Laura": 92, "Edwin": 89}print("\nAllgrades:", grades)print("\nSteve'scurrentgrade:", grades[ "Steve" ])grades[ "Steve" ] = 90print("Steve'snewgrade:", grades[ "Steve" ])grades[ "Michael" ] = 93print("\nDictionarygradesaftermodification:")print(grades)del grades[ "John" ]print("\nDictionarygradesafterdeletion:")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("Thedictionaryitemsare:(mD.items())")print(mD.items())print("\nThedictionarykeysare:(mD.keys())")print(mD.keys())print("\nThedictionaryvaluesare:(print (mD.values()))")print(mD.values())print("\nUsing a forlooptogetdictionaryitems:")forkeyin 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 {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'} Thedictionaryitemsare:(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')]) Thedictionarykeysare:(mD.keys()) dict_keys([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) Thedictionaryvaluesare:(print (mD.values())) dict_values(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']) Using a forlooptogetdictionaryitems: 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')]) # 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("Thedictionaryitemsare:(mD.items())")print(mD.items())print("\nThedictionarykeysare:(mD.keys())")print(mD.keys())print("\nThedictionaryvaluesare:(print (mD.values()))")print(mD.values())print("\nUsing a forlooptogetdictionaryitems:")forkeyin mD.keys():print( "mD[", key, "] =", mD[key])print("--print(mD.get(2))---")print(mD.get(2))print("--mD.popitem()---")mD.popitem()print(mD.items())

  17. Passing Lists to Functions Lists, Tuples and Dictionaries def modifyList( bList ):for i in range( len( bList ) ): bList[ i ] *= 2def modifyElement( element ): element *= 2aList = [ 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 ] *= 2def modifyElement( element ): element *= 2aList = [ 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

More Related