Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright (c) 2017 by Dr. E. Horvath

Similar presentations


Presentation on theme: "Copyright (c) 2017 by Dr. E. Horvath"— Presentation transcript:

1 Copyright (c) 2017 by Dr. E. Horvath
Introduction to Lists Lists are collections of data, they are indexable, they are sliceable, and they are mutable. Indexable means that elements of the list are accessible by index number. Mutable means that the list can be changed once it has been created; the values of elements can be changed, elements can be appended to or removed from the list, and so forth. If you know a programming language such as C or Java then you are already familiar with arrays. Lists are similar to arrays only they are much more powerful. Whereas an array can be declared to hold only one kind of data type, lists can hold any kind of data type. (There are arrays in Python as well, available as part of the pylab module.) Copyright (c) 2017 by Dr. E. Horvath

2 Copyright (c) 2017 by Dr. E. Horvath
Declaring a List A list is declared with square brackets: the_list = [ ] Notice the naming convention; the name of the list should end with an underscore followed by the word list. This convention is not enforced by the Python interpreter, but following this convention will make your code much more readable. You can also declare a list with the elements given in the declaration statement: pi_information_list = ['James Rockford', ' ', 4, , '29 Cove Rd., Malibu, CA']] Copyright (c) 2017 by Dr. E. Horvath

3 Accessing an Element of a List
Let's suppose you have a list of student test scores and you wish to access the elements of the list: test_score_list = [82.0,96.0,79.0,65.0,100.0,86.0 ] An element can be accessed in the following way: test_score_list[index] The first element in any list corresponds to index = 0. Copyright (c) 2017 by Dr. E. Horvath

4 Accessing an Element of a List: An Example
test_score_list = [82.0,96.0,79.0,65.0,100.0,86.0 ] bonus = 0.95 for index in range(0, 6): new_score = test_score_list[index]+bonus print(index, ' ', test_score_list[index],' ',new_score) Copyright (c) 2017 by Dr. E. Horvath

5 Appending Elements to a List
Let's suppose you create a list without any elements initially and you want to allow a user to append elements to the list. You append elements using the method append. print('Create a grocery list. When finished, enter exit') grocery_list = [ ] while True: item = input('Enter a grocery item: ') if item == 'exit': print('Thank you for your custom') break else: grocery_list.append(item) print('Your grocery bag contains: ') for item in grocery_list: print(item) Copyright (c) 2017 by Dr. E. Horvath

6 Appending Elements to a List
Make twelve pressure measurements, one every second, and append each measurement to the list. Calculate the average of those measurements. from sense_hat import SenseHat from time import sleep sense = SenseHat() pressure_list = [ ] pressure_sum = 0 for count in range(0,12): pressure = sense.get_pressure() pressure_sum += pressure pressure_list.append(pressure) sleep(1) pressure_avg = pressure_sum/12.0 print('Average pressure: ',pressure_avg) Copyright (c) 2017 by Dr. E. Horvath

7 Copyright (c) 2017 by Dr. E. Horvath
Using List Functions Lists are one kind of collection. There are four functions that work with any collection: len(C), min(C), max(C), and sum(C). The function len returns the collection length, min returns the minimum element, max returns the maximum element, sum returns the sum of the list elements. Copyright (c) 2017 by Dr. E. Horvath

8 Copyright (c) 2017 by Dr. E. Horvath
Using List Functions test_score_list = [82.0,96.0,79.0,65.0,100.0,86.0 ] length = len(test_score_list) print('Number of elements in list: ',length) minimum = min(test_score_list) print('Minimum element in list ',minimum) maximum = max(test_score_list) print('Maximum element in list ', maximum) sum_elements = sum(test_score_list) print('Sum of the elements in list: ',sum_elements) The function sum can be used only if all elements are numbers. Copyright (c) 2017 by Dr. E. Horvath

9 List Operators: Concatenation
Two lists can be concatenated together using the + operator. compsci_student_list=['Atalanta Armstrong', 'Hiram J. Washburn', 'Aurora Borealis', 'Johann Apfelbaum', 'Cressida deMarnier', 'Lucas McCullough'] club_accounts_list=[ , , , ,567.09] the_club_list = compsci_student_list + club_accounts_list for element in the_club_list: print(element) Copyright (c) 2017 by Dr. E. Horvath

10 List Operators: Replication
The contents of a list can be replicated by multiplying the list by an integer. In the following snippet of code, the original list is multiplied by 2. This means that every element in the list is replicated twice, and all these elements are then stored in the new list, new_number_of_members_list. number_of_members_list=[25, 5,34,120] new_number_of_members_list = number_of_members_list * 2 for element in new_number_of_members_list: print(element) #The new list will be [25, 5, 34, 120, 25, 5, 34, 120] Copyright (c) 2017 by Dr. E. Horvath

11 List Operators: Testing for Membership
Membership in a list is tested for using the keyword, in. You've already seen examples of this keyword on the previous slides. Consider the following list: russian_composers_list = ['Tchaikowsky', 'Borodin', 'Mussorgsky', 'Rimsky-Korsakov'] 'Borodin' in russian_composers_list #This returns True 'Wagner' in russian_composers_list #This returns False The keyword, in, can be used as part of a for statement, thereby creating a loop that iterates over every element in the list for composer in russian_composers_list: print(composer) Copyright (c) 2017 by Dr. E. Horvath

12 List Operators: Comparing Lists
The comparison operators- <, >, <=, >=, ==, and != - can be used to compare two lists.. Consider the following lists: russian_composers_list = ['Tchaikowsky', 'Borodin', 'Mussorgsky', 'Rimsky-Korsakov'] german_composers_list = ['Beethoven','Bach','Brahms','Wagner','Mendelssohn'] russian_composers_list > german_composers_list This comparison returns True because the letter T follows the letter B. *Please note that the above comparison is not intended as any kind of commentary on the talents of any of these composers. These examples are simply intended to show how comparison operators work. Copyright (c) 2017 by Dr. E. Horvath

13 List Operators: Comparing Lists cont'd
temperature_1_list = [89, 88, 75, 63, 68] temperature_2_list = [86, 101, 98, 92, 91, 94] temperature_1_list < temperature_2_list The comparison is False because the first element in temperature_1_list is greater than the first element in temperature_2_list. Let's suppose we change the first element in temperature_1_list to 86 and then compare the two lists. temperature_1_list[0] = 86 The comparison is now True because the first elements in each are equal to each other, but the second element of temperature_1_list is certainly less than the second element of temperature_2_list. Copyright (c) 2017 by Dr. E. Horvath

14 List Operators: Comparing Lists with Different Data Types
data_center_list = ['Professor Pernilla Kipper',' ', 63.45, 68] it_center_list = ['Professor Harvey Quackenbush', ' ', 92.89, 91, 94] data_center_list > it_center_list These lists are composed of elements of different data types. The first element in each list is a string, so this comparison is valid and will be True since the letter P follows the letter H. Let's suppose we change the first element in it_center_list to an integer. it_center_list[0] = 0 This comparison is NOT valid because the Python interpreter cannot compare the two different types of data. Consequently, a TypeError will occur. Copyright (c) 2017 by Dr. E. Horvath

15 Lists: A Method in the Madness
You've already seen an example of the append method on a few of the previous slides. Here are the other methods: index(x) returns the index of the first element that is equal to x. An error is thrown if there is no such element. count(x) returns the number of elements that are equal to x insert(i,x) inserts an element,x, at the specified index, I. remove(x) removes the first element, x, in the list. An error is thrown if there is no such element. Copyright (c) 2017 by Dr. E. Horvath

16 Lists: A Method in the Madness cont'd
reverse() reverses the elements in the list. sort() sorts the elements in the list. pop() removes the element at the end of the list and returns that item, and the number of elements in the list is decreased by one. extend(C) appends a collection to the end of the list.. Copyright (c) 2017 by Dr. E. Horvath

17 Lists: A Method in the Madness Example
Try out the following code: german_composers_list = ['Beethoven','Bach','Brahms','Wagner','Mendelssohn'] for composer in german_composers_list: print(composer) german_composers_list.sort() print(german_composers_list.index('Brahms')) Copyright (c) 2017 by Dr. E. Horvath

18 Lists: A Method in the Madness Example Cont'd
german_composers_list.remove('Beethoven') for composer in german_composers_list: print(composer) print(german_composers_list.count('Wagner')) german_composers_list.insert(3,'The Scorpions') Copyright (c) 2017 by Dr. E. Horvath


Download ppt "Copyright (c) 2017 by Dr. E. Horvath"

Similar presentations


Ads by Google