Presentation is loading. Please wait.

Presentation is loading. Please wait.

Final words on Lists.

Similar presentations


Presentation on theme: "Final words on Lists."— Presentation transcript:

1 Final words on Lists

2 Sorting items in a list We discussed how Python has a function for sorting out a list and that this could make our lives so much easier

3 Sorting items in a list my_list = [‘Donald’, ‘Bryan’, ‘Andrew’, ‘Mike’] my_list.sort( ) print(my_list) >> [‘Andrew’, ‘Bryan’, ‘Donald’, ‘Mike’] ** Notice that a new list is not created, rather the list you called is rearranged in alphabetical order

4 Find the position of an item in a list
You can also find the position (by index) of an item in a list We will use the “index” method This method takes one argument, an element to search for and returns an integer value, equivalent to the index of the item The index method will raise an exception if the item searched for is not found

5 Find the position of an item in a list
Example: my_list = [“pizza”, “pie”, “cake”] if “pie” in my_list: location = my_list.index(“pie”) print(“pie is at position #”, location) else: print(“not found!”)

6 Programming Challenge
Given that the following lists match up with one another (the items are listed in the same order of their respective prices), write a product price lookup program. products = [‘peanut butter’, ‘jelly’, ‘bread’] prices = [3.99, 2.99, 1.99]

7 Grabbing the largest/smallest items in a list
Python also has two built in functions that allow you to get the highest and lowest values in a list prices = [3.99, 2.99, 1.99] biggest = max(prices) smallest = min(prices) print(smallest, “up to”, biggest)

8 Grabbing the largest/smallest items in a list
These functions also work with strings, but the max( ) function will return the string with greatest ASCII value (meaning, closest to the end of the alphabet) and the min( ) will return the string that would appear first in the dictionary Recall that when comparing strings, Python will compare one character at a time You cannot use the max( ) and min( ) functions when working with lists of varying data types (comparing a float to a string will raise an exception)

9 Grabbing the largest/smallest items in a list
products = [‘bananas’, ‘apples’, ‘donuts’, ‘carrots’, ‘asparagus’] biggest = max(products) smallest = min(products) print(smallest, “to”, biggest) >> apples to donuts

10 Roulette Roulette is a game where a ball is rolled around a circular track – eventually the ball will come to a stop in a slot that is labeled with the numbers 0 to 36 Gamblers can bet on an individual number – if they win, they win a large prize (35:1)

11 Roulette Write a program that asks the user for a number between 0 and 36 Then spin the roulette 1000 times. Find out how many times the user’s # came up Tell the user the most frequent number and the least frequent number that came up

12 Programming Challenge
Write a program that takes all the elements in a list and reverses them In other words: prices = [8, 6, 4, 5, 3, 1, 2, 7] newlist = [7, 2, 1, 3, 5, 4, 6, 8]

13 Reversing items in a list
You can also reverse the order of the items in a list by using “reverse” This will not sort the list in reverse order – it will simply shuffle the elements of a list such that the first will be last and the last will be first prices = [3.99, 2.99, 1.99] prices.reverse( ) print(prices) >> [1.99, 2.99, 3.99]

14 Splitting a string Sometimes, you are given long strings of information that need to be “parsed” in a particular way For example: x = “Donald, Seok, Math Teacher” This string contains three pieces of information that are each separated by a comma

15 Splitting a string We can use a technique called “splitting” to “unpack” a string and extract it’s individual values. The trick is to isolate a separator character that can be used to delimit the data you want to extract. x = “Donald, Seok, Math Teacher” splitstring = x.split(“ , ”) print(splitstring) >> [‘Donald’, ‘Seok’, ‘Math Teacher’]

16 Programming Challenge
The following string represents the test scores of a student scores = “95, 100, 67, 33, 88” Write a program that: Prints out the average score Print out the highest and lowest score Drops the lowest score and prints out the student’s average without that score

17 Joining a list back into a string
You can reverse the “split” process and turn a list back into a string You must create a new string variable with the separator you wish to have between the elements of the list you are joining x = [‘a’, ‘b’, ‘c’] s = ‘,’ # new variable with comma separator (this can be anything) y = s.join(x) # join method called on string object, with list as argument print(y) >> a,b,c

18 Lists in lists As we briefly mentioned before, we can have lists stored in other lists This can be helpful in storing multiple pieces of data, that are multiple pieces of data For example: if you wanted a list of students for this class, in which each student would have three characteristics: gender, hair color, town

19 Lists in lists Ezra = [“F”, “brown”, “River Edge”]
Matt = [“M”, “black”, “River Edge”] Mark = [“M”, “brown”, “Oradell”] Pd1 = [Ezra, Matt, Mark] Here, Pd1 is the encompassing list that holds the list denoting each student

20 Lists in lists Ezra = [“F”, “brown”, “River Edge”]
Matt = [“M”, “black”, “River Edge”] Mark = [“M”, “brown”, “Oradell”] Pd1 = [Ezra, Matt, Mark] print(Pd1[2][0]) When seeking a specific value within a list that’s in a list, you use two indices, starting with the more encompassing list and going top down

21 Dictionaries Dictionaries are very similar to lists
The only difference really is that items in a dictionary are indexed by keywords set by the programmer and not by ascending numbers starting from zero

22 Dictionaries – Syntax When we set a dictionary, we use { } instead of [ ] char = {‘name’: ‘Charizard’, ‘type’: ‘fire’, ‘trainer’: ‘Ash’} print( char[‘type’] ) >> fire Dictionaries can be slightly annoying to create because of the use of so many delimiters but can become helpful in a more complex situation with many keys

23 So, why use Dictionaries?
You may come to realize that dictionaries are seemingly useless and if anything are just more tedious to write up in Python However, when dealing with very large databases, in which each item holds various characteristics, dictionaries can be really helpful Also, you will notice that lists require a specific order, where as dictionaries can be mixed up

24 Dictionaries char = {‘name’: ‘Charizard’, ‘type’: ‘fire’, ‘trainer’: ‘Ash’} bulb = {‘trainer’: ‘Brock’, ‘name’: ‘Bulbasaur’, ‘type’: ‘grass’} squir = {‘name’: ‘Squirtle’, ‘trainer’: ‘Max’, ‘type’: ‘water’} print(bulb[‘type’]) Notice how all the keys are out of order but each element can still be referenced by calling it’s specific key

25 Changing values in a dictionary
If you want to change a value in a dictionary, you call it’s specific key char = {‘name’: ‘Charizard’, ‘type’: ‘fire’, ‘trainer’: ‘Ash’} char[‘trainer’] = “Mr. Seok” print( “Charizard’s new trainer is now”, char[‘trainer’] ) >> Charizard’s new trainer is now Mr. Seok

26 Adding values to a dictionary
Adding a value into a dictionary is pretty simple, you would use the same notation as changing a value but with a new key char = {‘name’: ‘Charizard’, ‘type’: ‘fire’, ‘trainer’: ‘Ash’} char[‘level’] = ‘10,000’ print( “Charizard is level”, char[‘level’] ) print(char) >> Charizard is level 10,000 char = {‘name’: ‘Charizard’, ‘type’: ‘fire’, ‘trainer’: ‘Ash’, ‘level’: ’10,000’}

27 Removing values from a dictionary
If you want to remove a value from a dictionary, you can use the del method char = {‘name’: ‘Charizard’, ‘type’: ‘fire’, ‘trainer’: ‘Ash’} del char[‘trainer’] print( char ) >> {‘name’: ‘Charizard’, ‘type’: ‘fire’}

28 Printing the keys of a dictionary
In the event the user doesn’t know the keys to your dictionary/code, you can print out just the keys so the user knows what types they can reference in the code squir = {‘name’: ‘Squirtle’, ‘trainer’: ‘Max’, ‘type’: ‘water’, ‘level’: 5} print( list( squir.keys() ) ) >> [‘name’, ‘type’, ‘trainer’, ‘level’]

29 Dictionaries in Dictionaries
You can put dictionaries inside of a dictionary The syntax can become confusing and reallyyy annoying … but again serves it’s purposes in real world applications char = {‘name’: ‘Charizard’, ‘type’: ‘fire’, ‘trainer’: ‘Ash’} bulb = {‘trainer’: ‘Brock’, ‘name’: ‘Bulbasaur’, ‘type’: ‘grass’} squir = {‘name’: ‘Squirtle’, ‘trainer’: ‘Max’, ‘type’: ‘water’} Pokemon = {‘poke1’: char, ‘poke2’: bulb, ‘poke3’: squir} print( Pokemon[‘poke3’][‘type’] ) >> water

30 Example Code

31 Create a Pokedex! Create a database on Python that stores Pokemon and their characteristics


Download ppt "Final words on Lists."

Similar presentations


Ads by Google