Lists

• a list is a sequential collection of values, which are indexed. The values have an order. values are called elements. The values can be any data type. Lists are called heterogeneous because of that. Strings by contrast are homogeneous because all their elements are characters.
• List Values
• lists are enclosed in square brackets []
• list elements can be any data type in any order
• list elements can be lists too!
• empty list = []
• List Length
• len is a function that tells you how many elements in a list (or string)
• counts each sublist as ONE element
• Accessing Elements
• subscripts work with lists just like with strings
• start numbering at zero
• also are numbered from right end, backwards with negative subscripts
• syntax error in Active Code: 3 (chp09_02)
• note that a subscript indexes ONE element of the list
• example: a = [5, 9, [9,3], 4],
so a[2] is a list = [9,3]
so you could say a[2][0] (which would be 9)
note that the result is an integer, not a list
• example: lst = ["hat", "rat", "bat"]
lst[2] = "bat"
so lst[2].upper() is "BAT" (another string)
as before upper does not change lst[2]
• List Membership
• use "in" and "not in" for membership in a list
• names = ["James", "Bob", "Sally"], "James" in names is True
• "Jam" in names is False - the in operator works with elements as whole things
• Concatenation and Repetition
• the + and * operators work like with strings
• + gives a longer list, not two sublists
• List Slices
• slices work as with strings
• returns a list not a string!
• syntax error in ActiveCode:6 (chp09_6) missing underscores
• leave off the first argument to slice, starts at the left end of list
• leave off the second argument to slice, goes to the end of the list
• Lists are Mutable
• lists CAN be changed
• individual elements can have new values assigned to them
• a slice of a list can also have new values assigned to them all at one time
• mylist[1:3] = ['joe','bob'] will replace mylist[1] with 'joe' and mylist[2] with 'bob'
• can also get rid of elements by assigning them the empty list
mylist[4:6] = [] will take out mylist[4] and mylist[5]
• can also insert more elements in the list by assigning them to an empty slice at the desired location
mylist[1:1] = ['sam','ted'] will make the list two elements longer
• List Deletion
• del statement (not a method) which uses the position to remove elements
• del listname[index] or del listname[slice]
• Objects and References
• Aliasing
• just as with graphics objects or other objects,
• if you assign the same list to more than one variable, you do not make a copy of the list
• you have two names for the same list
• either identifier can be used to change the list
• called aliasing
• Cloning Lists
• if don't want aliasing to happen, can fix it with the slice operator
• b = a[:] will make a NEW copy of the list a and call it b
• b is NOT an alias, but a different list
• another way to prevent an alias from happening
• use a function called deepcopy
• must import a library "from copy import *"
• list3 = deepcopy(mylist)
• will make a new copy of the list
• also useful when working with other types of objects
• Repetition and References
• a common way to create a list with lots of entries, all the same value
• mylist = [0] * 100
• gives 100 elements, all of them 0
• mylist = ['a','b'] * 50 gives 100 elements, half 'a' and half 'b'
• but be careful!
• if you put a list "inside" a list, with the repetition operator you get aliases NOT more copies of the list!
• square = [[0] * 10] * 5 gives you 50 "references" but only 10 real elements
• List Methods
• note that some of these change the list
• append - changes the list
mylist.append("joe") makes mylist longer
• sort - changes the list
mylist.sort() makes mylist in ascending order
• index - like "find" for a string
• returns location of an item in a list
• warning - if the item is NOT in the list, program crashes!
• min, max - only work on numeric data in a list
• count - counts number of occurrences of an item in a list
• The Return of L-Systems - ignore
• Append versus Concatenate
• append changes the list by adding an element to the right end of it
mylist.append("ralph") will have a new element value "ralph"
a stand alone statement
• concatenation uses the + sign, must work on two lists
just saying mylist + "ralph" will not work - "ralph" is a string not a list
mylist + ["ralph"] will work, but is just an expression
to get the list to change, would need mylist = mylist+["ralph"]
• append is a little more efficient because it does not remake the list with a new element on the end, it just adds it to the original list
concatenation has to make a copy of the old list, stick on the new element and then get rid of ("garbage collect") the old list
• Lists and for loops
• just like with strings, can use with for loops in two ways
• either for i in mylist: i will be each element in the list
• or for i in range(len(mylist)): i will be integers which index all the elements of the list
• Using Lists as Parameters
• a "pure" function
• up until now you have thought of parameters as "one way" variables
• you sent data into a function by matching arguments with parameters when a function is called
• the only way to get things out of a function was through the return statement
• any changes you made to parameters in the function were only temporary, lost when the function was over
• book calls this a "pure" function
• a function with mutable parameters
• it IS possible to permanently change parameters which are mutable
• lists are mutable!
• many languages allow for this possibility
• the "usual" way we've used parameters is called "pass by value"
• means make a copy of the values of the arguments into the parameters
• data only goes INTO the function
• if you change the parameter permanently, that is called "pass by reference"
• be aware this is always possible when you pass a list as a parameter
• if your function DOES change a parameter, then document it!
• the documentation is a warning to "anyone who uses this function, your argument WILL be changed!"
• an example
• ```	def main():
lst = [1,2,3,8,7]
fun(lst)
print(lst)

def fun(mylist):
for i in range(len(mylist)):
mylist[i] += 10
```
• there is no return for that function definition
• the changes in mylist are actually changes in lst
• the list WILL be changed in the main!
• Which is Better?
• in general, they both have their uses
• C++ only allows ONE value to be returned from a function
• in C++, if you have more than one thing to return, you MUST use the pass by reference method to return values - through the parameter list
• in Python, it is up to you - just document what you are doing
• Functions that Produce Lists
• a common pattern for a function that works with lists
• initialize a new list to an empty list []
• use a loop
• create a new element for the new list
• append the new element to the new list
• return the resulting new list
• example:
• ```    #function to report the words in a list which are palindromes
#assumes you have a function which returns True when its argument is a palindrome
def pallist (wordlist):
newlist = []
for i in range(len(wordlist)):
if palindrome(wordlist[i]):
newlist.append(wordlist[i])
return newlist
```
• List Comprehensions
• a unique feature of Python
• syntax: [ expression for item in sequence if condition]
• the "if condition" part is optional
• expression usually involves the "item" mentioned after the "for"
• sequence can be a range, a list, a file
• the result of this is a list
• how to create a two-dimensional list using a comprehension
• new2Dlist = [[0] * cols for i in range(rows)]
• where cols is the number of columns in each row and rows is the number of rows in the 2-d list
• 0 can be any value, it will be the initial value in each element
• Nested Lists
• Strings and Lists
• split method (from chapter 9 Lists)
• split is a string method
• works on a string
• produces a list of strings
• delimiter is not included in the strings, they are eliminated
• delimiter used can be changed
• .split() will use ANY whitespace for delimiter
• .split(" ") will use exactly ONE space for delimiter (this does NOT say the same thing as the previous line!)
• .split("\t") will use the tab character as delimiter
• .split("ab") will use "ab" as delimiter
• if st is "123ab456ab789", st.split("ab") returns a list ["123", "456", "789"]
• list Type Conversion Function
• Tuples as Return Values

Arrays in Python slides