Changes

Jump to: navigation, search

OPS435 Python Lab 3

84 bytes added, 13:21, 14 August 2017
PART 2 - Manipulating Items in Lists
ipython3
</source>
:#Let's perform a simple change to a list element. Issue the following in the ipython shell:<sourcelang="python">
courses = [ 'uli101', 'ops235', 'ops335', 'ops435', 'ops535', 'ops635' ]
courses[0]
courses
</source>It might be useful to change a list element-by-element, but there are other more efficient methods of changing a list (for example: using functions). You will now use the '''dir()''' and '''help()''' functions to see what functions and attributes are available for manipulating lists. The '''help()''' function will also give us tips on how to use those functions. For example, you can use issue help(list-name) in order to see what functions are available to use for that list specific list.<br><br>
:#Issue the following:<sourcelang="python">
dir(courses)
help(courses)
</source>Below are some examples of using functions to '''manipulate''' lists. Take time to see how each function can be a useful tool for making changes to existing lists.<br><br>
:#Issue the following:<sourcelang="python">
help(courses.append)
courses.append('ops235') # Add a new item to the end of the list
</source>In addition to using functions to manipulate lists, there are functions that are useful to provide '''information''' regarding the list such as number of elements in a list, the smallest value and largest value in a list.<br><br>
:#Issue the following:<sourcelang="python">
list_of_numbers = [ 1, 5, 2, 6, 8, 5, 10, 2 ]
len(list_of_numbers) # Returns the length of the list
min(list_of_numbers) # Returns the smallest value in the list
max(list_of_numbers) # Returns the largest value in the list
</source>In addition to manipulating and obtaining characteristics of a list, it is also useful to be able to '''perform searches''' for values within lists and obtain the location of values for elements contained within a list. The '''index()''' function allows searching inside a list for a value, it will return the index number of the first occurence. <sourcelang="python">
number = 10
help(list_of_numbers.index)
list_of_numbers.index(number) # Return index of the number searched for
</source>One common annoyance that can occur when performing searches are '''error messages''' when performing a search for an element that happens NOT to exist in the list. A good way to prevent those type of errors is to use a logic statement to check to see if the value for an element is in a list, then the appropriate search can be performed for that existing element value.<br><br>
:#Issue the following:<sourcelang="python">
list_of_numbers = [ 1, 5, 2, 6, 8, 5, 10, 2 ]
number = 7

Navigation menu