Copyright (c) 2017 by Dr. E. Horvath

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Sequences The range function returns a sequence
Lists Introduction to Computing Science and Programming I.
1 Sequences A sequence is a list of elements Lists and tuples – Lists mutable – Tuples immutable Sequence elements can be indexed with subscripts – First.
2/28/2008. >>> Overview Arrays in Python – a.k.a. Lists Ranges are Lists Strings vs. Lists Tuples vs. Lists Map-Reduce Lambda Review: Printing to a file.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Lists in Python.
Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.
Lecture 21 - Tuples COMPSCI 101 Principles of Programming.
Lists Computers and Programming. Agenda What is a list? How to access elements in the list? The for statement Operations on lists Looping with.
Chapter 7 Lists and Tuples. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Data Structures.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Lists and Tuples Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Built-in Data Structures in Python An Introduction.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 8 Working.
10. Python - Lists The list is a most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Tuples and Dictionaries Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
CSc 110, Autumn 2016 Lecture 15: lists Adapted from slides by Marty Stepp and Stuart Reges.
String and Lists Dr. José M. Reyes Álamo.
Data types: Complex types (List)
Python: Experiencing IDLE, writing simple programs
Sequences and Indexing
Containers and Lists CIS 40 – Introduction to Programming in Python
CMSC201 Computer Science I for Majors Lecture 12 – Lists (cont)
JavaScript: Functions.
CSC 108H: Introduction to Computer Programming
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Lists Part 1 Taken from notes by Dr. Neil Moore
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Bryan Burlingame 03 October 2018
Bryan Burlingame Halloween 2018
Lecture 15: lists Adapted from slides by Marty Stepp and Stuart Reges
8 – Lists and tuples John R. Woodward.
Lecture 18 Arrays and Pointer Arithmetic
Data Structures – 1D Lists
4. sequence data type Rocky K. C. Chang 16 September 2018
CS 1111 Introduction to Programming Fall 2018
String and Lists Dr. José M. Reyes Álamo.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Lecture 19: lists Adapted from slides by Marty Stepp and Stuart Reges
Topics Sequences Introduction to Lists List Slicing
Lists Part 1 Taken from notes by Dr. Neil Moore
CS 1111 Introduction to Programming Spring 2019
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Topics Sequences Lists Copying Lists Processing Lists
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Python Review
Copyright (c) 2017 by Dr. E. Horvath
Text Copyright (c) 2017 by Dr. E. Horvath
Introduction to Dictionaries
Copyright (c) 2017 by Dr. E. Horvath
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Enclosing delimiters Python uses three style of special enclosing delimiters. These are what the Python documentation calls them: {} braces # Sometimes.
Tuple.
Introduction to Computer Science
Presentation transcript:

Copyright (c) 2017 by Dr. E. Horvath Copying a List There are several valid ways of copying a list, including shallow copying and deep copying. One way that is not valid is to simply assign one list to the other; the problem with this is that both lists will reference the same memory even though they have different names. Consider the following code: first_list = [94.3,340.0,13.09,103.5] second_list = first_list If you make a change to first_list, then that change will also be reflected in second_list because they point to the same memory. For example, first_list.append(8248.1) for elem in first_list: print(elem) for elem in second_list: Copyright (c) 2017 by Dr. E. Horvath

Copyright (c) 2017 by Dr. E. Horvath Shallow Copying 1 One way to shallow copy is to create the new list consisting of the same number of elements in the list you are copying. Then copy the original list element by element into the new list. first_list = [94.3,340.0,13.09,103.5] second_list = [0]*len(first_list) count= 0 while count < len(first_list): second_list[count] = first_list[count] count += 1 first_list.append(8484.1) for elem in first_list: print(elem) for elem in second_list: Copyright (c) 2017 by Dr. E. Horvath

Shallow Copying Caveat! Let's suppose that one of the elements in first_list is itself a list. first_list = [94.3,340.0,13.09,103.5,['Jeremiah','Bullfrog'] ] second_list = [] for item in first_list: second_list.append(item) first_list[4][0] = 'Joshua' first_list.append(8484.1) for elem in first_list: print(elem) for elem in second_list: Changing an element in the list in first_list will cause the same change to the list in second_list. When the elements are printed out, 'Joshua' will appear in both. This is because the reference to the list is copied rather than the copy. Note, however, that only first_list will have an element of 8484.1. Copyright (c) 2017 by Dr. E. Horvath

Copyright (c) 2017 by Dr. E. Horvath Deep Copying Use the deepcopy function to copy the actual content of every element first_list = [94.3,340.0,13.09,103.5,['Jeremiah','Bullfrog'] ] import copy second_list = copy.deepcopy(first_list) first_list.append(8484.1) first_list[4][0] = 'Joshua' for elem in first_list: print(elem) for elem in second_list: Changing an element in the list in first_list will cause the same change to the list in second_list. When the elements are printed out, 'Joshua' will appear in both. This is because the reference to the list is copied. Copyright (c) 2017 by Dr. E. Horvath

Passing a List to a Function def update_list_function(original_list,value): new_list = [] # create a new empty list for i in range(0,len(original_list)): new_list.append(original_list[i] * value) # multiply each element in the original_list by the value and append it to the new_list return new_list def main(): price_list = [3.4,2.99,4.44] # declare the list and assign the values updated_list = update_list_function(price_list,2.0) print("updated_list") for v in updated_list: print(v) main() Copyright (c) 2017 by Dr. E. Horvath

Passing a List to a Function Alternate Version def update_list_function(original_list,value): new_list = [] * len(original_list) # create a new_list that has the same number of elements as the original_list for i in range(0,len(original_list)): new_list[i] = original_list[i] * value # multiply each element by the value return new_list def main(): price_list = [3.4,2.99,4.44] updated_list = update_list_function(price_list,2.0) print("updated_list") for i in range(0,len(updated_list)): print(updated_list[i]) main() Copyright (c) 2017 by Dr. E. Horvath

Tuples? Lists? What's the Difference? A list is a mutable collection of data, which means that elements can be changed, removed, or added. A tuple is an immutable list, which means that elements cannot be changed, removed, or added. In the previous set of slides, you learned how to use the methods append, insert, remove, pop, extend, reverse, and sort. Because these methods change the elements of a collection, they do not work on tuples. However, the functions sum, len, min, and max work the same way as they do for lists. And operators such as >, <, concatentation, and replication work on tuples as well. Tuples are also indexable. Copyright (c) 2017 by Dr. E. Horvath

Tuples? Lists? What's the Difference? The elements in a tuple can be of any variable type. Why use a tuple when you could use a list? Tuples help you preserve the integrity of data. Copyright (c) 2017 by Dr. E. Horvath

Copyright (c) 2017 by Dr. E. Horvath Declaring a Tuple A tuple is declared with commas: my_tuple = 45, 'Radio Hut', 354e-09, 392.45 You can also declare the tuple with the following statement: my_tuple = (45, 'Radio Hut', 354e-09, 392.45) However, it is the commas that indicate to the Python interpreter that the collection is a tuple. The parentheses are not necessary to create a tuple. Copyright (c) 2017 by Dr. E. Horvath

Accessing Tuple Elements Let's use the tuple declared on the previous slide: my_tuple = 45, 'Radio Hut', 354e-09, 392.45, 'Pizza Shack' for item in my_tuple: print(item) Modify the declaration statement for the tuple by enclosing the elements on the right side by parentheses. You'll notice that the presence of parentheses won't affect the execution of the code. Copyright (c) 2017 by Dr. E. Horvath

Functions that Work on Tuples The functions len(C), min(C), max(C), and sum(C) work on tuples, but there are restrictions regarding the use of min, max, and sum. The function sum only works if all the elements are numbers. The functions min and max only work if the element types are the same. my_tuple = 45, 'Radio Hut', 354e-09, 392.45, 'Pizza Shack' The only function of the four that works on this particular tuple is the len function. len(my_tuple) Copyright (c) 2017 by Dr. E. Horvath

Functions that Work on Tuples: Another Example A tuple contains the daily high pressure readings for one week: hi_press_tuple = 987.3, 998.1, 999.0, 1010.1, 1008.4,1005.2,1006.7 print('Number of measurements '+ str(len(hi_press_tuple))) print('Minimum of measurements '+str(min(hi_press_tuple))) print('Maximum of measurements '+str(max(hi_press_tuple))) measurement_ave = sum(hi_press_tuple)/len(hi_press_tuple) print('Average of measurements '+str(measurement_ave)) Copyright (c) 2017 by Dr. E. Horvath

Starting with a List and Ending up with a Tuple You might be writing to code to collect sensor readings, but you would ultimately like to store the data as a tuple. One way of handling this would be to declare a list and append each measurement to the list. Once all of the data have been collected you would then use the tuple constructor to create a new tuple. In the following, ten compass readings are collected and then stored as a tuple. Copyright (c) 2017 by Dr. E. Horvath

Starting with a List and Ending up with a Tuple from sense_hat import SenseHat from time import sleep sense = SenseHat() compass_list = [ ] for comp in range (0,10): compass_list.append(sense.get_compass()) sleep(1) compass_tuple = tuple(compass_list) for reading in compass_tuple: print(reading) Copyright (c) 2017 by Dr. E. Horvath

Copyright (c) 2017 by Dr. E. Horvath Indexing Tuples You can access the elements of a tuple by index exactly the same way as you did for lists. my_tuple = 45, 'Radio Hut', 354e-09, 392.45, 'Pizza Shack' for i in range(0,5): print(my_tuple[i]) Copyright (c) 2017 by Dr. E. Horvath

Indexing Tuples: Another Example In the following snippet of code, a set of temperature readings in Celsius is stored in a tuple. Each temperature is then converted to Fahrenheit and printed out to the Python shell. ctemp_tuple = 24.3, 22.4, 19.4, 26.4, 29.5, 31.2, 30.6 for i in range(0,5): ftemp = 9/5 * ctemp_tuple[i] + 32 print(ftemp) Copyright (c) 2017 by Dr. E. Horvath

Indexing Tuples: Tuples Can't Be Changed Let's suppose you convert the temperatures from Celsius to Fahrenheit and then try to store those converted temperatures in the tuple. The following code does NOT work and the Python interpreter will throw an error. Had the following data collection been declared as a list rather than a tuple, the code would run just fine. temp_tuple = 24.3, 22.4, 19.4, 26.4, 29.5, 31.2, 30.6 for i in range(0,5): temp_tuple[i] = 9/5 * temp_tuple[i] + 32 print(temp_tuple[i]) Copyright (c) 2017 by Dr. E. Horvath

Tuple Operators: Concatenation Tuple operators work the same way as do list operators. So, we'll just look at a couple of examples: concatenation and replication. The first tuple contains relative humidity measurements and the second tuple contains opinions about the climate. The third tuple contains the concatenation of the first two tuples. rel_humidity_tuple = 56, 78, 86, 56, 99 opinion_tuple = 'pleasant', 'muggy', 'stifling', 'pleasant', 'I\'m moving' env_tuple = rel_humidity_tuple + opinion_tuple for elem in env_tuple: print(elem) Copyright (c) 2017 by Dr. E. Horvath

Tuple Operators: Replication The contents of a tuple can be replicated by multiplying the list by an integer. In the following snippet of code, the original tuple is multiplied by 3. This means that every element in the tuple is replicated twice, and all these elements are then stored in the new tuple, new_yaw_tuple. yaw_tuple= 323.4456, 354.0241, 346.3324 new_yaw_tuple = yaw_tuple * 3 for element in new_number_of_members_tuple: print(element) Copyright (c) 2017 by Dr. E. Horvath