Lists Introduction to Computing Science and Programming I.

Slides:



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

Container Types in Python
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
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.
Guide to Programming with Python
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Introduction to Python
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Guide to Programming with Python
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
COMPUTER SCIENCE FEBRUARY 2011 Lists in Python. Introduction to Lists Lists (aka arrays): an ordered set of elements  A compound data type, like strings.
Lists in Python.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
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.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
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 CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Built-in Data Structures in Python An Introduction.
CIT 590 Intro to Programming Lecture 5 – completing lists.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 8 Working.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 8: Fun with strings.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
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.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
String and Lists Dr. José M. Reyes Álamo.
User-Written Functions
Tuples and Lists.
Python - Lists.
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Containers and Lists CIS 40 – Introduction to Programming in Python
CMSC201 Computer Science I for Majors Lecture 12 – Lists (cont)
CSC 108H: Introduction to Computer Programming
CSC 108H: Introduction to Computer Programming
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Lists Part 1 Taken from notes by Dr. Neil Moore
Arrays, For loop While loop Do while loop
Introduction to Strings
Introduction to Strings
Object Oriented Programming COP3330 / CGS5409
File Handling Programming Guides.
Bryan Burlingame 03 October 2018
Bryan Burlingame Halloween 2018
Guide to Programming with Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
Data types Numeric types Sequence types float int bool list str
8 – Lists and tuples John R. Woodward.
4. sequence data type Rocky K. C. Chang 16 September 2018
Intro to Computer Science CS1510 Dr. Sarah Diesburg
String and Lists Dr. José M. Reyes Álamo.
Topics Sequences Introduction to Lists List Slicing
Lists Part 1 Taken from notes by Dr. Neil Moore
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CHAPTER 4: Lists, Tuples and Dictionaries
Introduction to Computer Science
Topics Sequences Introduction to Lists List Slicing
Python Review
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Class code for pythonroom.com cchsp2cs
Introduction to Strings
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Introduction to Computer Science
Presentation transcript:

Lists Introduction to Computing Science and Programming I

Lists To this point we have used simple variables to store data. One variable storing a string, int, or some other type of value. To this point we have used simple variables to store data. One variable storing a string, int, or some other type of value. Using variables can become cumbersome if you want to store more data. If you wanted to store the name and id for 10 students you would need twenty separate variables. Using variables can become cumbersome if you want to store more data. If you wanted to store the name and id for 10 students you would need twenty separate variables.

Lists Python provides a data structure called a list to store multiple values. Python provides a data structure called a list to store multiple values. Lists can store values of any data type and a single list can store values of different types. Lists can store values of any data type and a single list can store values of different types. Lists are stored in a variable as with the other data types. Lists are stored in a variable as with the other data types.

Lists Some examples Some examples numberList = [20, 15, 10, 15, 0] numberList = [20, 15, 10, 15, 0] wordList = [“some”,”words”,”are”,”these”] wordList = [“some”,”words”,”are”,”these”] boolList = [True, False, True] boolList = [True, False, True] mixedList = [“hello”, 1.5, True, “x”, [1,2,3]] mixedList = [“hello”, 1.5, True, “x”, [1,2,3]] Note the representation for lists, they are surrounded by square brackets with their contents separated by commas Note the representation for lists, they are surrounded by square brackets with their contents separated by commas Since a list is just another data type, lists can have lists as members. Since a list is just another data type, lists can have lists as members.

Lists Accessing an element of a list is done in the same way as accessing a single character from a string. The first element has index 0. Accessing an element of a list is done in the same way as accessing a single character from a string. The first element has index 0. numbers = [2,4,6,8,10] numbers = [2,4,6,8,10] numbers[0] is 2, numbers[2] is 6 numbers[0] is 2, numbers[2] is 6 You can also assign new values to elements of a list, something you can’t do with a string. You can also assign new values to elements of a list, something you can’t do with a string. numbers[0] = -5 numbers[0] = -5 numbers[4] = 0 numbers[4] = 0 #now numbers is [-5,4,6,8,0] #now numbers is [-5,4,6,8,0]

Lists The + and * operators work with lists as they do with strings. The + and * operators work with lists as they do with strings. +, “concatenation” +, “concatenation” [2, 4, 8] + [16, 32, 64] is [2, 4, 8, 16, 32, 64] [2, 4, 8] + [16, 32, 64] is [2, 4, 8, 16, 32, 64] * [1,2,3] * 3 is [1,2,3,1,2,3,1,2,3] [1,2,3] * 3 is [1,2,3,1,2,3,1,2,3]

Lists The len() function used with strings will tell you how many elements a list contains. The len() function used with strings will tell you how many elements a list contains. myList = [1, 4, 11, 13] myList = [1, 4, 11, 13] len(myList) returns 4 len(myList) returns 4 This allows us to loop through the elements of a list as we have with strings. This allows us to loop through the elements of a list as we have with strings. for i in range(len(myList)): print myList[i]

Lists Here are a couple more basic functions for manipulating lists. Here are a couple more basic functions for manipulating lists. append is used to add a single element to the end of a list. append is used to add a single element to the end of a list. names = [“Chris”,”Matt”,”Steph”] names = [“Chris”,”Matt”,”Steph”] names.append(“Jesse”) names.append(“Jesse”) names.append(“Rob”) names.append(“Rob”) del can be used to delete specific elements del can be used to delete specific elements del names[2] del names[2]

Lists vs Strings Strings act in a lot of ways like a list of characters, but there are important differences. Strings act in a lot of ways like a list of characters, but there are important differences. You can’t make changes to a string, adding, removing, or changing characters, without recreating the entire string. You can’t make changes to a string, adding, removing, or changing characters, without recreating the entire string. We’ll look at these differences more a bit later. We’ll look at these differences more a bit later.

Lists in For Loops All of the for loops we’ve written so far have been of the form All of the for loops we’ve written so far have been of the form for i in range(5): …. …. All the range function does is return a list of numbers, [0,1,2,3,4] in this case, and the code in the loop is run after assigning each element of the list to i All the range function does is return a list of numbers, [0,1,2,3,4] in this case, and the code in the loop is run after assigning each element of the list to i

Lists in For Loops You can use any list when you write a for loop. Every element of the list will be assigned to the variable you give and the code will be executed. You can use any list when you write a for loop. Every element of the list will be assigned to the variable you give and the code will be executed. for x in [1,2,3]: print x print x cities = [“Toronto”,”Vancouver”,”Montreal”] for city in cities: print city print city

Slices We’ve already seen how to access single elements of a list by using their index. We’ve already seen how to access single elements of a list by using their index. You can access multiple elements of a list at the same time by using the process called slicing. You can access multiple elements of a list at the same time by using the process called slicing.

Slices Typical slices Typical slices numbers = [“one”, “two”, “three”, “four”] numbers[0] is “one” numbers[0:2] is [“one”, “two”] numbers[1:4] is [“two”, “three”, “four”] Notice that the slice [a:b] gives the element a through the element b-1. This is the same logic the range function uses if you give it two numbers. Notice that the slice [a:b] gives the element a through the element b-1. This is the same logic the range function uses if you give it two numbers.

Slices If you don’t give a beginning or ending index, the slice will start at the beginning or end of the list. If you don’t give a beginning or ending index, the slice will start at the beginning or end of the list. numbers = [“one”, “two”, “three”, “four”] numbers[:2] is [“one”, “two”] numbers[1:] is [“two”, “three”, “four”]

Slices You can use negative numbers as indexes. In this case Python starts counting backwards from the end of the list. You can use negative numbers as indexes. In this case Python starts counting backwards from the end of the list. [“one”, “two”, “three”, “four”] [“one”, “two”, “three”, “four”] index: index:

Slices A couple examples with negative indexes A couple examples with negative indexes numbers = [“one”, “two”, “three”, “four”] In this case [0:2] and [-4:-2] are identical In this case [0:2] and [-4:-2] are identical numbers[-4:-2] is [“one”, “two”] [:-1] gives all but the last element [:-1] gives all but the last element numbers[:-1] is [“one”, “two”, “three”]

Slices You can assign lists to a slice. You can assign lists to a slice. numbers = [“one”, “two”, “three”, “four”] numbers[1:3] = [“A”, “B”] numbers now is [“one”, “A”, “B”, “four”] You don’t have to replace a slice with a list with the same number of elements You don’t have to replace a slice with a list with the same number of elements numbers = [“one”, “two”, “three”, “four”] numbers[1:3] = [“A”] numbers now is [“one”, “A”, “four”]

Slices As with single elements you can delete slices of a list. As with single elements you can delete slices of a list. numbers = [“one”, “two”, “three”, “four”] del numbers[1:3] numbers is now [“one”, “four”]

Slices and Strings The same rules for slicing lists can be used for slicing strings. However, you can’t assign values to a slice of a string. The same rules for slicing lists can be used for slicing strings. However, you can’t assign values to a slice of a string. s = “Hello World” s[1:5] is “ello” s[-5:] is “World” s[1:5] = “i” would cause an error.

For Loops and Strings For loops can use strings in the same manner as they use lists. For loops can use strings in the same manner as they use lists. for c in “abc”: print c print c Each character in the string will be assigned in turn to the variable c Each character in the string will be assigned in turn to the variable c

Strings vs Lists The central difference between strings and lists is that a list can be changed in- place, that is we can alter it without creating a new list. This can not be done with strings. The central difference between strings and lists is that a list can be changed in- place, that is we can alter it without creating a new list. This can not be done with strings.

Mutability The term used to describe this difference is mutability. The term used to describe this difference is mutability. An object such as a list, that can be changed is mutable. An object such as a list, that can be changed is mutable. Strings, which cannot be changed, are immutable Strings, which cannot be changed, are immutable

Mutability numList = numList + [5] stars = stars + “*” In lines of code such as these Python creates an entirely new list/string and stores it in a variable. The original list/string is removed from memory In lines of code such as these Python creates an entirely new list/string and stores it in a variable. The original list/string is removed from memorynumList.append(5) Something different is happening here. Instead of creating an entirely new list we are calling a method of numList that alters the list. Something different is happening here. Instead of creating an entirely new list we are calling a method of numList that alters the list. deleting or assigning new values to an element/slice of a list also do not cause the list to be recreated from scratch deleting or assigning new values to an element/slice of a list also do not cause the list to be recreated from scratch

Mutability In general using these methods of altering a list in-place are more efficient since they do not require Python to make a copy of the list to evaluate an expression. In general using these methods of altering a list in-place are more efficient since they do not require Python to make a copy of the list to evaluate an expression. strings, our simple data types (int, Bool…), and some objects are immutable. strings, our simple data types (int, Bool…), and some objects are immutable. Lists and some other objects are mutable. Lists and some other objects are mutable.

References So far we’ve just looked at variables as storing a value. So far we’ve just looked at variables as storing a value. Now we’re going to get into some detail on how Python handles variables behind the scenes. Now we’re going to get into some detail on how Python handles variables behind the scenes.

References Every variable in Python is a reference to a specific spot in memory where the contents of the variable are actually stored. Every variable in Python is a reference to a specific spot in memory where the contents of the variable are actually stored. print x+5 When a variable is part of an expression Python retrieves the contents from the location in memory specified by the variable. Once it has them it can complete the expression When a variable is part of an expression Python retrieves the contents from the location in memory specified by the variable. Once it has them it can complete the expression

References x = x = 2 * n In lines of code such as these Python evaluates the expression on the right side, stores the value in memory, and then has x point to that place in memory. In lines of code such as these Python evaluates the expression on the right side, stores the value in memory, and then has x point to that place in memory.

References

References Copying variables Copying variables Simple assignment, x = y Simple assignment, x = y Function parameter, print some_function(x) Function parameter, print some_function(x) In these cases Python just copies the location of memory to the new variable. In these cases Python just copies the location of memory to the new variable. That means that Python doesn’t need to copy the entire contents of a variable which could be a list containing thousands of elements. That means that Python doesn’t need to copy the entire contents of a variable which could be a list containing thousands of elements.

References

References Aliases Aliases When two variables point to the same location in memory, as with the last example, they are called aliases of each other. When two variables point to the same location in memory, as with the last example, they are called aliases of each other. With immutable data types this doesn’t cause any complications because the contents of the location in memory can’t be changed. With immutable data types this doesn’t cause any complications because the contents of the location in memory can’t be changed. However, with mutable data, such as a list, if two variables are aliases of the same list, changes to one variable will be seen by both. However, with mutable data, such as a list, if two variables are aliases of the same list, changes to one variable will be seen by both.

References

References This aliasing means that if a function takes a list as an argument, changes to that list inside the function will be seen outside the function. This aliasing means that if a function takes a list as an argument, changes to that list inside the function will be seen outside the function. This should be avoided unless the function makes absolutely clear that a list passed to it will be changed. This should be avoided unless the function makes absolutely clear that a list passed to it will be changed.

References Cloning Cloning If you want to make an identical but separate copy of a variable, you must clone it. If you want to make an identical but separate copy of a variable, you must clone it. With lists this can be done by doing the following. With lists this can be done by doing the following. newList = oldList[:] Since there is no start or end index for the slice, Python copies the entire list. newList and oldList now point to separate copies of the list. Since there is no start or end index for the slice, Python copies the entire list. newList and oldList now point to separate copies of the list.