lists introduction to computing science and programming i

34
Lists Lists Introduction to Computing Introduction to Computing Science and Programming I Science and Programming I

Post on 18-Dec-2015

214 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Lists Introduction to Computing Science and Programming I

ListsLists

Introduction to Computing Introduction to Computing Science and Programming IScience and Programming I

Page 2: Lists Introduction to Computing Science and Programming I

ListsLists

To this point we have used simple To this point we have used simple variables to store data. One variable variables to store data. One variable storing a string, int, or some other storing a string, int, or some other type of value.type of value.

Using variables can become Using variables can become cumbersome if you want to store cumbersome if you want to store more data. If you wanted to store more data. If you wanted to store the name and id for 10 students you the name and id for 10 students you would need twenty separate would need twenty separate variables. variables.

Page 3: Lists Introduction to Computing Science and Programming I

ListsLists

Python provides a data structure Python provides a data structure called a list to store multiple values.called a list to store multiple values.

Lists can store values of any data Lists can store values of any data type and a single list can store type and a single list can store values of different types.values of different types.

Lists are stored in a variable as with Lists are stored in a variable as with the other data types.the other data types.

Page 4: Lists Introduction to Computing Science and Programming I

ListsLists

Some examplesSome 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 Note the representation for lists, they are surrounded by square brackets with their surrounded by square brackets with their contents separated by commascontents separated by commas

Since a list is just another data type, lists Since a list is just another data type, lists can have lists as members.can have lists as members.

Page 5: Lists Introduction to Computing Science and Programming I

ListsLists

Accessing an element of a list is done in the Accessing an element of a list is done in the same way as accessing a single character same way as accessing a single character from a string. The first element has index 0.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 6numbers[0] is 2, numbers[2] is 6

You can also assign new values to elements You can also assign new values to elements of a list, something you can’t do with a of a list, something you can’t do with a string.string. numbers[0] = -5numbers[0] = -5 numbers[4] = 0numbers[4] = 0 #now numbers is [-5,4,6,8,0]#now numbers is [-5,4,6,8,0]

Page 6: Lists Introduction to Computing Science and Programming I

ListsLists

The + and * operators work with lists The + and * operators work with lists as they do with strings.as they do with strings. +, “concatenation”+, “concatenation”

[2, 4, 8] + [16, 32, 64] is [2, 4, 8, 16, 32, [2, 4, 8] + [16, 32, 64] is [2, 4, 8, 16, 32, 64]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]

Page 7: Lists Introduction to Computing Science and Programming I

ListsLists

The len() function used with strings will The len() function used with strings will tell you how many elements a list tell you how many elements a list contains.contains. myList = [1, 4, 11, 13]myList = [1, 4, 11, 13] len(myList) returns 4len(myList) returns 4

This allows us to loop through the This allows us to loop through the elements of a list as we have with elements of a list as we have with strings.strings.for i in range(len(myList)):for i in range(len(myList)):

print myList[i]print myList[i]

Page 8: Lists Introduction to Computing Science and Programming I

ListsLists

Here are a couple more basic Here are a couple more basic functions for manipulating lists.functions for manipulating lists. append is used to add a single element append is used to add a single element

to the end of a list.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 del can be used to delete specific elementselements

del names[2]del names[2]

Page 9: Lists Introduction to Computing Science and Programming I

Lists vs StringsLists vs Strings

Strings act in a lot of ways like a list Strings act in a lot of ways like a list of characters, but there are of characters, but there are important differences.important differences.

You can’t make changes to a string, You can’t make changes to a string, adding, removing, or changing adding, removing, or changing characters, without recreating the characters, without recreating the entire string.entire string.

We’ll look at these differences more We’ll look at these differences more a bit later.a bit later.

Page 10: Lists Introduction to Computing Science and Programming I

Lists in For LoopsLists in For Loops

All of the for loops we’ve written so All of the for loops we’ve written so far have been of the formfar have been of the form

for i in range(5):for i in range(5):

… …..

All the range function does is return All the range function does is return a list of numbers, [0,1,2,3,4] in this a list of numbers, [0,1,2,3,4] in this case, and the code in the loop is run case, and the code in the loop is run after assigning each element of the after assigning each element of the list to ilist to i

Page 11: Lists Introduction to Computing Science and Programming I

Lists in For LoopsLists in For Loops

You can use any list when you write a You can use any list when you write a for loop. Every element of the list for loop. Every element of the list will be assigned to the variable you will be assigned to the variable you give and the code will be executed.give and the code will be executed.

for x in [1,2,3]:for x in [1,2,3]: print xprint x

cities = [“Toronto”,”Vancouver”,”Montreal”]cities = [“Toronto”,”Vancouver”,”Montreal”]for city in cities:for city in cities: print cityprint city

Page 12: Lists Introduction to Computing Science and Programming I

SlicesSlices

We’ve already seen how to access We’ve already seen how to access single elements of a list by using single elements of a list by using their index.their index.

You can access multiple elements of You can access multiple elements of a list at the same time by using the a list at the same time by using the process called slicing.process called slicing.

Page 13: Lists Introduction to Computing Science and Programming I

SlicesSlices

Typical slicesTypical slicesnumbers = [“one”, “two”, “three”, “four”]numbers = [“one”, “two”, “three”, “four”]numbers[0] is “one”numbers[0] is “one”numbers[0:2] is [“one”, “two”]numbers[0:2] is [“one”, “two”]numbers[1:4] is [“two”, “three”, “four”]numbers[1:4] is [“two”, “three”, “four”]

Notice that the slice [a:b] gives the Notice that the slice [a:b] gives the element a through the element b-1. element a through the element b-1. This is the same logic the range This is the same logic the range function uses if you give it two function uses if you give it two numbers.numbers.

Page 14: Lists Introduction to Computing Science and Programming I

SlicesSlices

If you don’t give a beginning or If you don’t give a beginning or ending index, the slice will start at ending index, the slice will start at the beginning or end of the list.the beginning or end of the list.

numbers = [“one”, “two”, “three”, “four”]numbers = [“one”, “two”, “three”, “four”]

numbers[:2] is [“one”, “two”]numbers[:2] is [“one”, “two”]

numbers[1:] is [“two”, “three”, “four”]numbers[1:] is [“two”, “three”, “four”]

Page 15: Lists Introduction to Computing Science and Programming I

SlicesSlices

You can use negative numbers as You can use negative numbers as indexes. In this case Python starts indexes. In this case Python starts counting backwards from the end of counting backwards from the end of the list.the list.

[“one”, “two”, “three”, “four”][“one”, “two”, “three”, “four”]

index: 0 1 2 3index: 0 1 2 3

index: -4 -3 -2 -1 index: -4 -3 -2 -1

Page 16: Lists Introduction to Computing Science and Programming I

SlicesSlices

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

In this case [0:2] and [-4:-2] are identicalIn this case [0:2] and [-4:-2] are identicalnumbers[-4:-2] is [“one”, “two”]numbers[-4:-2] is [“one”, “two”]

[:-1] gives all but the last element[:-1] gives all but the last elementnumbers[:-1] is [“one”, “two”, “three”]numbers[:-1] is [“one”, “two”, “three”]

Page 17: Lists Introduction to Computing Science and Programming I

SlicesSlices

You can assign lists to a slice.You can assign lists to a slice.numbers = [“one”, “two”, “three”, “four”]numbers = [“one”, “two”, “three”, “four”]numbers[1:3] = [“A”, “B”]numbers[1:3] = [“A”, “B”]numbers now is [“one”, “A”, “B”, “four”]numbers now is [“one”, “A”, “B”, “four”]

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

Page 18: Lists Introduction to Computing Science and Programming I

SlicesSlices

As with single elements you can As with single elements you can delete slices of a list.delete slices of a list.

numbers = [“one”, “two”, “three”, “four”]numbers = [“one”, “two”, “three”, “four”]

del numbers[1:3]del numbers[1:3]

numbers is now [“one”, “four”]numbers is now [“one”, “four”]

Page 19: Lists Introduction to Computing Science and Programming I

Slices and StringsSlices and Strings

The same rules for slicing lists can be The same rules for slicing lists can be used for slicing strings. However, used for slicing strings. However, you can’t assign values to a slice of a you can’t assign values to a slice of a string.string.

s = “Hello World”s = “Hello World”

s[1:5] is “ello”s[1:5] is “ello”

s[-5:] is “World”s[-5:] is “World”

s[1:5] = “i” would cause an error.s[1:5] = “i” would cause an error.

Page 20: Lists Introduction to Computing Science and Programming I

For Loops and StringsFor Loops and Strings

For loops can use strings in the same For loops can use strings in the same manner as they use lists.manner as they use lists.

for c in “abc”:for c in “abc”:

print cprint c

Each character in the string will be Each character in the string will be assigned in turn to the variable cassigned in turn to the variable c

Page 21: Lists Introduction to Computing Science and Programming I

Strings vs ListsStrings vs Lists

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

Page 22: Lists Introduction to Computing Science and Programming I

MutabilityMutability

The term used to describe this The term used to describe this difference is mutability.difference is mutability. An object such as a list, that can be An object such as a list, that can be

changed is mutable.changed is mutable. Strings, which cannot be changed, are Strings, which cannot be changed, are

immutableimmutable

Page 23: Lists Introduction to Computing Science and Programming I

MutabilityMutability

numList = numList + [5]numList = numList + [5]stars = stars + “*”stars = stars + “*”

In lines of code such as these Python creates an In lines of code such as these Python creates an entirely new list/string and stores it in a variable. entirely new list/string and stores it in a variable. The original list/string is removed from memoryThe original list/string is removed from memory

numList.append(5)numList.append(5) Something different is happening here. Instead Something different is happening here. Instead

of creating an entirely new list we are calling a of creating an entirely new list we are calling a method of numList that alters the list.method of numList that alters the list.

deleting or assigning new values to an deleting or assigning new values to an element/slice of a list also do not cause the list to element/slice of a list also do not cause the list to be recreated from scratchbe recreated from scratch

Page 24: Lists Introduction to Computing Science and Programming I

MutabilityMutability

In general using these methods of In general using these methods of altering a list in-place are more efficient altering a list in-place are more efficient since they do not require Python to make since they do not require Python to make a copy of the list to evaluate an a copy of the list to evaluate an expression.expression.

strings, our simple data types (int, strings, our simple data types (int, Bool…), and some objects are immutable.Bool…), and some objects are immutable.

Lists and some other objects are Lists and some other objects are mutable.mutable.

Page 25: Lists Introduction to Computing Science and Programming I

ReferencesReferences

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

Now we’re going to get into some Now we’re going to get into some detail on how Python handles detail on how Python handles variables behind the scenes.variables behind the scenes.

Page 26: Lists Introduction to Computing Science and Programming I

ReferencesReferences

Every variable in Python is a reference to a Every variable in Python is a reference to a specific spot in memory where the contents specific spot in memory where the contents of the variable are actually stored.of the variable are actually stored.

print x+5print x+5

When a variable is part of an expression When a variable is part of an expression Python retrieves the contents from the Python retrieves the contents from the location in memory specified by the location in memory specified by the variable. Once it has them it can complete variable. Once it has them it can complete the expressionthe expression

Page 27: Lists Introduction to Computing Science and Programming I

ReferencesReferences

x = 3 + 6x = 3 + 6

x = 2 * nx = 2 * n In lines of code such as these Python In lines of code such as these Python

evaluates the expression on the right evaluates the expression on the right side, stores the value in memory, side, stores the value in memory, and then has x point to that place in and then has x point to that place in memory.memory.

Page 28: Lists Introduction to Computing Science and Programming I

ReferencesReferences

Page 29: Lists Introduction to Computing Science and Programming I

ReferencesReferences

Copying variablesCopying variables Simple assignment, x = ySimple assignment, x = y Function parameter, print some_function(x)Function parameter, print some_function(x)

In these cases Python just copies the In these cases Python just copies the location of memory to the new variable. location of memory to the new variable.

That means that Python doesn’t need to That means that Python doesn’t need to copy the entire contents of a variable copy the entire contents of a variable which could be a list containing thousands which could be a list containing thousands of elements.of elements.

Page 30: Lists Introduction to Computing Science and Programming I

ReferencesReferences

Page 31: Lists Introduction to Computing Science and Programming I

ReferencesReferences

AliasesAliases When two variables point to the same When two variables point to the same

location in memory, as with the last location in memory, as with the last example, they are called aliases of each example, they are called aliases of each other.other.

With immutable data types this doesn’t With immutable data types this doesn’t cause any complications because the cause any complications because the contents of the location in memory can’t be contents of the location in memory can’t be changed.changed.

However, with mutable data, such as a list, if However, with mutable data, such as a list, if two variables are aliases of the same list, two variables are aliases of the same list, changes to one variable will be seen by both.changes to one variable will be seen by both.

Page 32: Lists Introduction to Computing Science and Programming I

ReferencesReferences

Page 33: Lists Introduction to Computing Science and Programming I

ReferencesReferences

This aliasing means that if a function This aliasing means that if a function takes a list as an argument, changes takes a list as an argument, changes to that list inside the function will be to that list inside the function will be seen outside the function.seen outside the function.

This should be avoided unless the This should be avoided unless the function makes absolutely clear that function makes absolutely clear that a list passed to it will be changed.a list passed to it will be changed.

Page 34: Lists Introduction to Computing Science and Programming I

ReferencesReferences

CloningCloning If you want to make an identical but If you want to make an identical but

separate copy of a variable, you must separate copy of a variable, you must clone it.clone it.

With lists this can be done by doing the With lists this can be done by doing the following.following.

newList = oldList[:]newList = oldList[:] Since there is no start or end index for Since there is no start or end index for

the slice, Python copies the entire list. the slice, Python copies the entire list. newList and oldList now point to newList and oldList now point to separate copies of the list.separate copies of the list.