Lists Introduction to Computing Science and Programming I

  • Slides: 34
Download presentation
Lists Introduction to Computing Science and Programming I

Lists Introduction to Computing Science and Programming I

Lists n n To this point we have used simple variables to store data.

Lists n n 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.

Lists n n n Python provides a data structure called a list to store

Lists n n n 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 are stored in a variable as with the other data types.

Lists n Some examples n n n number. List = [20 , 15 ,

Lists n Some examples n n n number. List = [20 , 15 , 10 , 15 , 0] word. List = [“some”, ”words”, ”are”, ”these”] bool. List = [True, False, True] mixed. List = [“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 Since a list is just another data type, lists can have lists as members.

Lists n Accessing an element of a list is done in the same way

Lists n 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. n numbers = [2, 4, 6, 8, 10] 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. n numbers[0] = -5 numbers[4] = 0 #now numbers is [-5, 4, 6, 8, 0]

Lists n The + and * operators work with lists as they do with

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

Lists n The len() function used with strings will tell you how many elements

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

Lists n Here a couple more basic functions for manipulating lists. n append is

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

Lists vs Strings n n n Strings act in a lot of ways like

Lists vs Strings n n n 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. We’ll look at these differences more a bit later.

Lists in For Loops n All of the for loops we’ve written so far

Lists in For Loops n All of the for loops we’ve written so far have been of the form for i in range(5): …. n 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 n You can use any list when you write a

Lists in For Loops n 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 cities = [“Toronto”, ”Vancouver”, ”Montreal”] for city in cities: print city

Slices n n We’ve already seen how to access single elements of a list

Slices n n 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.

Slices n Typical slices numbers = [“one”, “two”, “three”, “four”] numbers[0] is “one” numbers[0:

Slices n Typical slices numbers = [“one”, “two”, “three”, “four”] numbers[0] is “one” numbers[0: 2] is [“one”, “two”] numbers[1: 4] is [“two”, “three”, “four”] n 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 n If you don’t give a beginning or ending index, the slice will

Slices n 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 n You can use negative numbers as indexes. In this case Python starts

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

Slices n A couple examples with negative indexes numbers = [“one”, “two”, “three”, “four”]

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

Slices n You can assign lists to a slice. numbers = [“one”, “two”, “three”,

Slices n You can assign lists to a slice. numbers = [“one”, “two”, “three”, “four”] numbers[1: 3] = [“A”, “B”] numbers now is [“one”, “A”, “B”, “four”] n 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 n As with single elements you can delete slices of a list. numbers

Slices n 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 n The same rules for slicing lists can be used for

Slices and Strings n 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 n For loops can use strings in the same manner

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

Strings vs Lists n The central difference between strings and lists is that a

Strings vs Lists n 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 n The term used to describe this difference is mutability. An object such

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

Mutability num. List = num. List + [5] stars = stars + “*” n

Mutability num. List = num. List + [5] stars = stars + “*” n 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 num. List. append(5) n n Something different is happening here. Instead of creating an entirely new list we are calling a method of num. List 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

Mutability n n n In general using these methods of altering a list in-place

Mutability n n n 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. Lists and some other objects are mutable.

References n n So far we’ve just looked at variables as storing a value.

References n n 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.

References n Every variable in Python is a reference to a specific spot in

References n 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 n 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=3+6 x=2*n n In lines of code such as these Python evaluates the

References x=3+6 x=2*n 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.

References

References

References n Copying variables n n Simple assignment, x = y Function parameter, print

References n Copying variables n n Simple assignment, x = y Function parameter, print some_function(x) 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.

References

References

References n Aliases When two variables point to the same location in memory, as

References n Aliases When two variables point to the same location in memory, as with the last example, they are called aliases of each other. n With immutable data types this doesn’t cause any complications because the contents of the location in memory can’t be changed. n 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. n

References

References

References n n This aliasing means that if a function takes a list as

References n n 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.

References n Cloning If you want to make an identical but separate copy of

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