lists in python. lists a list is a sequential collection of values, it is a data structure each...

38
Lists in Python

Upload: letitia-pitts

Post on 12-Jan-2016

215 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Lists in Python

Page 2: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Lists

• A list is a sequential collection of values, it is a data structure

• Each value has a location (an index)• Indexes range from 0 to n-1 (where n is the

length of the list) and from -1 to -n • Lists are heterogeneous = values can be of any

type (strings are homogeneous because their elements are characters)

Page 3: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

List syntax

• Values are enclosed in [], myList = [3, ‘a’, True]• One list can contain another• Empty list = []• Any type of data can be in the list• You usually refer to a list by elements, that is

with the []. You can refer to a list by its name (as one whole thing) when passing it as an argument to a function.

Page 4: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

List semantics

• Lists are mutable, that is, elements can be changed

• Individual elements can be changed the same way any variable can be changed, with an assignment statement

• myList = [1,9, ‘a’, 4, 7]• m = 3• myList[m] = 99• myList[m+1] = 88

Page 5: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Length function

• The same as with the string type, len (lst) will return an integer, the number of elements in the list, from zero up to some max int value

• If a list contains a sublist, it counts as one element L = [1, [3, 4], 7] has 3 elements

• You call it as part of another statement, for example, print(len(mylist))

Page 6: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Accessing elements of a list

• The index starts at 0 just like with a string and goes up to n-1 if there are n elements in the list

• They also can use negative subscripts, -1 is the last element on the right, -n on the left end

Page 7: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Lists in Python

Creating lists

Page 8: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Simple ways to create a list

• Hard code the values mylist = [3, 9, ‘a’, 7.2]• Using the replication operator– mylist = [0] * 100 (gives a list with 100 zeros)

• Use the split method on a string• Use the readlines method on a file• Put [] around a variable if my_num is 5, then [ my_num] is the list [5]

Page 9: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Append vs. Concatenate

• Both can be used to add to an existing list but their syntax is not the same

• The concatenate operator + uses two lists and creates a bigger one – You cannot say mylist = mylist + “joe”, it must be

mylist = mylist + [“joe”]• Append is a method which adds an element to

the right end of a list – any type of data– mylist.append(“3”) makes mylist one element longer

Page 10: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

List accumulation

• Either concatenation or append can be used with lists as accumulators

• Initialize the list variable as an empty list []• inside your loop either concatenate or append

the new item onto your list variable

Page 11: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

How to output a list

• Very simplest way – just print the name of the list– print(myList)– This results in output that has [] around it, quotes around strings

and commas between items• More often, the output needs each item without the

formatting around it• In this case, you need a loop that will process through the

list, one element at a time– see “Traversing a list”– You need either a for loop that presents elements one at a time

or a loop that provides the subscript for each element one at a time.

Page 12: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Lists in Python

List methods and functions

Page 13: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

List methodsMethod Semantics

list.append(x) Adds x to the right end of list, changes original list

list.sort() Sorts items of list, in place. Items must be comparable

list.reverse() Reverses order of items in list in place

list.index(x) Returns integer index of first (leftmost) occurrence of x

list.count(x) Returns integer count of number of occurrences of x in list

Page 14: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Notes about methods

• These methods, append, sort, reverse, all change the original list.

• If you need to retain the original list as well as keep the resulting list, use sorted(listname) and list(reversed(listname))

• Just as with strings, index will cause an exception and program crash if its search fails

Page 15: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

List functionsFunction Semantics

min (list) Returns the smallest element in the list, items must be comparable

max (list) Returns the largest element in the list, items must be comparable

sum (list) Returns the arithmetic total of all items in list, items must be numeric

sorted (list) Returns a new copy of list in ascending order, items must be comparable

reversed (list) Returns an iterator of the list in reverse order (use a list typecast to get the list)

Page 16: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Notes about functions and methods

• When the previous two tables say “items must be comparable”, it means they must all be of numeric type, or they must all be strings. Mixing them will cause an exception and crash

• When they say “in place” it means that it will change the original list.

• For the sum function, items can be integer or float

Page 17: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Lists in Python

Sequential and Random access of elements

Page 18: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Random vs. Sequential

• Lists have two ways to be accessed– random (direct)– sequential

• Both are useful in their place• If you need to access ALL elements of a list (either

in order or order doesn’t matter), sequential is the way to go because it is simpler

• Otherwise you need to access elements randomly

Page 19: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Examples

• sequentialfor i in range(5):

print(myList[i])• random

for i in [3, 2, 0, 4, 1]:print(myList[i])

Note that it is the order of elements accessed that makes it sequential or random, both will use the []

Page 20: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Lists in Python

Lists as Arguments/Parameters

Page 21: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Lists as arguments to functions

• Just like other data types, lists can be sent to functions as arguments

• The function must be aware of the fact that a parameter is a list, so it can treat it as a list (use subscripts)

• Lists are passed to functions in a different way than other arguments you have seen so far

Page 22: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Passed by value

• The process y ou have seen so far is that the values of arguments are copied into the spaces reserved for parameters

• The function can do anything you want with the copies

• The copies are deleted when the function finishes and returns

• This is called ‘passing arguments by value’

Page 23: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Passing by reference

• Lists are handled differently• Their address is sent to the function in the

place of a parameter• Using the address (also called the reference)

the function can change the elements of the list – in other words, the function is changing the original contents of the original list

• In other words, the list contents can be changed permanently

Page 24: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Python versus other languages

• In languages like C, C++ and Java, passing by reference is fairly common

• A main reason for this is that those languages can return no more than one value via a return statement

• If a function needs to return two things, it must use pass by reference to get one of the things back to the calling code

Page 25: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Python vs. other languages

• Python on the other hand can return many different values through the return statement

• Typically functions do not need to pass things by reference because of this fact

• The main thing to be aware of is that a function can change a list, which will affect the calling function’s variable. Most Python programmers would consider doing this a mistake by the programmer.

• If you do use passing by reference, document it WELL in the header, so that anyone using the function knows that a list argument can be changed!

Page 26: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Lists in Python

Selection Sort Algorithm

Page 27: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Sorting

• A very common activity for computers• Not just in business, sorting is used in

databases, graphics, simulations, games, etc.• Many different algorithms for sorting– different ones are better for sorting data in

different formats, environments, conditions• Python has a sort algorithm builtin, for lists

Page 28: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

So why learn a sort algorithm?

• Good exercise for manipulating lists• Not all languages have one builtin• Why selection sort?– one of the simpler algorithms– easy to debug if necessary

Page 29: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Selection sort for n elements (ascending)

• for n-1 passesfind the largest value in unsorted part of listswap it with the value at the end of the

unsorted part

There are variations based on using smallest instead of largest, on descending instead of ascending

Page 30: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Lists in Python

Parallel lists

Page 31: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Parallel lists

• This is a technique for using lists which goes back to the early days of programming

• It’s not new syntax, just a slightly different way to look at arrays

• Many languages have a restriction that an array can be only one type, an integer array, a string array, etc.

Page 32: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

• Sometimes the situation required storing both floats and strings, for example (GPAs and names).

• One piece of data, a GPA, belongs with another piece of data, a name.

• Since they could not be put in the same array, they were put in separate arrays, but in the same position.

Page 33: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Parallel arrays

• By using the same subscript for both arrays, you are referring to related data.

• The main thing to remember is if you move data around in one of the arrays, you must make the same moves in the other array

• Nothing in the language enforces this relationship, it’s up to your programming

Page 34: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Lists in Python

Two-dimensional arrays

Page 35: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Two dimensions

• You will sometimes have data which has a two-dimensional structure (days and hours for example, or rows and columns)

• You could store the data in one big list and keep track of the structure some other way but most modern languages provide a way to express the two dimensions directly

Page 36: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

List of lists

• In Python you can think of this structure as a list of lists

• mat = [[1,2,3], [5, 9, 2], [7, 8, 3], [6, 7, 0]]• Of course in Python any of these lists can be

any size (they don’t all have to be 3 elements long!)

• Typically a 2-d array is thought of as having so many rows and so many columns (a grid like Excel)

Page 37: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Syntax of 2-d arrays

• One way to create a 2-d array is as given on the last slide, just write it out

• Another that is quicker if you want to initialize all elements to one value:– mat2 = [[0] * 3 for i in range(4)]

creates a 2-d array with 4 rows, 3 columns full of zeros

0 0 0

0 0 0

0 0 0

0 0 O

Page 38: Lists in Python. Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to

Accessing elements of a 2-d array

• You use two subscripts, each in a pair of []• mat [2][1] is the element in the third row and

second column – just like 1-d arrays, they start numbering at [0][0]