lists in python. lists a list is a sequential collection of values, it is a data structure each...
Post on 12-Jan-2016
215 Views
Preview:
TRANSCRIPT
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 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)
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.
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
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))
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
Lists in Python
Creating lists
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]
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
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
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.
Lists in Python
List methods and functions
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
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
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)
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
Lists in Python
Sequential and Random access of elements
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
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 []
Lists in Python
Lists as Arguments/Parameters
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
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’
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
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
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!
Lists in Python
Selection Sort Algorithm
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
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
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
Lists in Python
Parallel lists
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.
• 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.
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
Lists in Python
Two-dimensional arrays
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
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)
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
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]
top related