Write My Paper Button

WhatsApp Widget

DATA STRUCTURES | My Assignment Tutor

17/03/20181DATA STRUCTURESStrings, lists, Tuples and MapsStrings■ Text in programming is what we call a string.■ Think of a string as a collection of letters■ Example of a string: “Hello World.”17/03/20182Creating strings■ In Python, we create a string by putting quotes (“”) around text■ Can also create strings by putting inverted commas (‘’) aroundthe text■ greetings … Continue reading “DATA STRUCTURES | My Assignment Tutor”

17/03/20181DATA STRUCTURESStrings, lists, Tuples and MapsStrings■ Text in programming is what we call a string.■ Think of a string as a collection of letters■ Example of a string: “Hello World.”17/03/20182Creating strings■ In Python, we create a string by putting quotes (“”) around text■ Can also create strings by putting inverted commas (‘’) aroundthe text■ greetings = “Hello Python”■ Str = “Python is fun”■ print(greetings + “, “ + Str )– Hello Python, Python is fun■ Str = “Today’s date is 1/1/2017”■ Str = ‘He said “we should not be complacent” after the election’Embedding value in strings■ To display a message using the contents of a variable, youcan embed values in a string using %s■ %s is a space holder for the value– yourAge= 28– message = ‘You are %s years old’– print(message %yourAge)– You are 28 years old17/03/20183Multiplying strings■ str = “Hello”■ print(str*3)– HelloHelloHelloLists■ A list is simply a sequence of values stored in a specific orderwith each value identified by its position in that order.■ So for an example consider the list of names of the studentsin a class■ Or the list of primes up to 60.■ Note that a list must be finite.■ Lists can grow as well as shrink in size■ A list is an improvement from a string as it can bemanipulated in various ways17/03/20184Creating a list■ A list can contain any data type■ A list is created with a comma separated values inside squarebrackets■ fibonacci= [ 1,1,2,3,5,8,13,21,34]■ languages = [‘Python’,’C#’,’VB.NET’,’C++’, ‘Java’]■ fibonacci– [1,1,2,3,5,8,13,21,34]8Python counts from zero[ 1, 1, 3, 5, 8 , 13 , 21 , 34 ]“index” 0 1 2 3 4 5 6 7“value”• Each individual item is identified by its position in the list.• Python, in common with many programming languages (but not all)starts its count from zero.• To keep yourself sane, we strongly recommend the language “itemnumber 3” instead of “the fourth item”.17/03/201859Looking things up in a list primes = [ 2, 3, 5, 7, 11, 13, 17, 19][ 2, 3, 5, 7, 11 , 13 , 17 , 19 ]0 1 2 3 4 5 6 7 primes217[ 0]indexprimes [ 6]square bracketsCounting from the end fibonacci= [ 1,1,2,3,5,8,13,21][ 1 , 1 , 2 , 3 , 5 , 8 , 23 , 21 ]0 1 2 3 4 5 6 721fibonacci[-1] getting at the last item-8 -7 -6 -5 -4 -3 -2 -1• Negative indices are used to count backwards from the end of the list.• In practice this is useful to find the last element in the list17/03/2018611Length of a listprimeslist8 len8(primes)0 7Maximumindex is 7len() function:length of list• Note that the length of a list is the number of items itcontains.• The largest legitimate index is one less than that becauseindices count from zero.12Changing a value in a list data = [‘alpha’, ‘beta’, ‘gamma’] data[2]‘gamma’ data[2] = ‘G’ data[2]‘G’ data[‘alpha’, ‘beta’, ‘G’]The listInitial valueChange valueCheck changeChanged list17/03/2018713Removing an entry from a list del data[1]• We can remove entries from the list with the “del” keyword data = [‘alpha’, ‘beta’, ‘gamma’] del data[1]data[‘alpha’,’gamma’]14Running off the end len(primes)8 primes[7]19 primes[8]Traceback (most recent call last):File “”, line 1, in IndexError: list index out of rangeType of error Description of error17/03/2018815Appending to a list primes[2, 3, 5, 7, 11, 13, 17, 19] primes primes[2, 3, 5, 7, 11, 13, 17, 19,. append (23)The list is now updated23 ]A function built into a list16Methodsobject . function (arguments)a function that hasspecial access tothe object’s data.Behaves justlike a function• These built in functions are called “methods” or, more precisely,“methods of the object” are used all over Python and are a generalconcept across an entire type of programming called “object orientedprogramming”.17/03/2018917Other methods on lists: reverse() numbers = [4, 7, 5, 1] numbers.reverse() print(numbers)[1, 5, 7, 4]The function doesn’treturn any value.It modifiesthe list itself.18Other methods on lists: sort() numbers = [4, 7, 5, 1] numbers.sort() print(numbers)[1, 4, 5, 7]Numerical order.The function does notreturn the sorted list.It sorts thelist itself.Try sorting a list of strings17/03/20181019Other methods on lists: insert() greek = [‘alpha’, ‘gamma’,0 1 2 greek.insert(‘delta’]Where to insert What to insert1, ‘beta’ ) greek[‘alpha’, ‘beta’, ‘gamma’, ‘delta’]0 1 DisplacedOther methods on lists: remove() numbers = [7, 4, numbers.remove print(numbers)[7, 4,8, 7, 2, 5, 4](8)7, 2, 5, 4]c.f. del numbers[2]Value to removeIndex to remove17/03/201811Concatenation newlist primes= primes + [23, 29, 31]primes = primes + [23, 29, 31]Create a new listUpdate the list+= [23, 29, 31]Augmented assignment22Creating lists from text list(‘Hello’)[‘H’, ‘e’, ‘l’, ‘l’, ‘o’]5 str Hello list51str H1str e1str l1str l1str o17/03/201812Tuples■ A tuple is a collection data type like a list■ It uses parentheses instead of square brackets■ fibonacci = (1, 1, 2, 3,5,8,13,21,34,55)■ print(fibonacci [5])■ 8■ Tuples are immutable – cant be changed.■ Why would you use a tuple instead of a list?■ Sometimes it is useful to use something that you know can neverchange.■ If you create a tuple with two elements inside, it will always have thosetwo elements inside.Dictionary■ A Python dictionary, a.k.a. map is also a collection of data likelists and tuples■ The pairs of items separated by colons are known as the“key” and “value”.■ The key is what you put in (the English word in this example)that you look up in the dictionary and the value is what youget out (the translation into Spanish in this example). en_to_es = { ‘cat’:’gato’ , ‘dog’:’perro’ } En _to_es[‘cat’]‘gato’17/03/201813Adding to a dictionary en_to_es en_to_es[‘mouse’] = ‘ratón’ en_to_es[‘mouse’]‘ratón’= { ‘cat’:’gato’ , ‘dog’:’perro’ }Initial dictionary has no ‘mouse’Adding ‘mouse’ to the dictionary• Adding key-value pairs to a dictionary is a lot easier than it is with lists.• With lists we needed to append on the end of a list.• With dictionaries, because there is no inherent order, we can simplydefine them with a simple expression on the left hand side.26Removing from a dictionary print(en_to_es){‘mouse’: ‘ratón’, del en_to_es[ print(en_to_es){‘mouse’: ‘ratón’, ‘cat’: ‘gato’}‘dog’: ‘perro’, ‘cat’: ‘gato’}‘dog’ ]We can use del to remove from a dictionary just as we did withlists.

Don`t copy text!
WeCreativez WhatsApp Support
Our customer support team is here to answer your questions. Ask us anything!
???? Hi, how can I help?