Methods#
string, list, & dictionary
in place vs not in place
relationship to functions
Class Question #1#
What will the following code snippet print?
def my_func(my_dictionary):
output = []
for item in my_dictionary:
value = my_dictionary[item]
output.append(value) #append method adds an item to end of a list
return output
# create dictionary and execute function
dictionary = {'first' : 1, 'second' : 2, 'third' : 3}
out = my_func(dictionary)
print(out)
A) [‘first’, ‘second’, ‘third’]
B) {1, 2, 3}
C) [‘first’, 1, ‘second’, 2, ‘third’, 3]
D) [1, 2, 3]
E) None
Methods#
Method Examples#
A method is a function applied directly to the object you call it on.
General form of a method:
object.method()
In other words: methods “belong to” an object.
# The `append` method, defined on lists
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
The method append()
is called directly on the list my_list
# append is a method for lists
# this will error with a string
my_string = 'cogs18'
my_string.append('!')
# The `is_integer()` method, defined on floats
12.0
12.3.is_integer()
# The `is_integer()` method, attempted on an integer
# this code will produce an error
my_int = 12
my_int.is_integer()
String Methods#
There are a whole bunch of string methods, all described here. We’ll review a few of the most commonly used here.
# Make a string all lower case
'aBc'.lower()
# Make a string all upper case
'aBc'.upper()
# Capitalize a string
'python is great'.capitalize()
# Find the index of where a string starts
'Hello, my name is'.find('name')
Class Question #2#
What will the following code snippet print out?
inputs = ['fIx', 'tYpiNg', 'lIkE', 'tHiS']
output = ''
for element in inputs:
output = output + element.lower() + ' '
output.capitalize()
A) ‘fix typing like this ‘
B) [‘fix’, ‘typing’, ‘like’, ‘this’]
C) ‘Fix typing like this ‘
D) ‘Fix typing like this’
E) ‘Fixtypinglikethis’
List Methods#
There are also a bunch of list methods, all described here. You’ve seen some of these before, but we’ll review a few of the most commonly used here.
# sort sorts integers in numerical orders
ints = [16, 88, 33, 40, 40, 40, 3]
ints.sort()
ints
ints.sort(reverse=True)
ints
# append adds to the end of a list
ints.append(2)
ints
# remove value from list
ints.remove(40)
ints
list.remove?
# reverse order of list
ints.reverse()
ints
Class Question #3#
What will the following code snippet print out?
list_string = ['a', 'c', 'd', 'b']
list_string.sort()
list_string.reverse()
list_string
A) [‘a’, ‘c’, ‘d’, ‘b’]
B) [‘a’, ‘b’, ‘c’, ‘d’]
C) [‘d’, ‘c’, ‘b’, ‘a’]
D) [‘d’, ‘b’, ‘a’, ‘c’]
E) [‘d’, ‘a’, ‘b’, ‘c’]
Dictionary Methods#
As with string and list methods, there are many described here that are helpful when working with dictionaries.
car = {
"brand": "BMW",
"model": "M5",
"year": 2019
}
# keys() returns the keys of a dictionary
car.keys()
#for key in cars
# get returns the value of a specified key
mod = car.get('model')
# equivalent
mod2 = car['model']
print(mod)
print(mod2)
# previously done this by indexing
print(car['model'])
# update adds a key-value pair
car.update({"color": "Black"})
print(car)
Class Question #4#
Assuming dictionary
is a dictionary that exists, what would the following accomplish:
dictionary.get('letter')
A) Return the key for the value ‘letter’ from
dictionary
B) Add the key ‘letter’ to
dictionary
C) Add the value ‘letter’ to
dictionary
D) Return the value for the key ‘letter’ from
dictionary
Class Question #5#
Which method would you use to add a new key-value pair to a dictionary?
A)
.append()
B)
.get()
C)
.keys()
D)
.update()
Methods: In Place vs Not In Place#
List methods that are in place#
# Reverse a list
my_list = ['a', 'b', 'c']
my_list.reverse()
#print(my_list)
# Sort a list
my_numbers = [13, 3, -1]
my_numbers.sort()
print(my_numbers)
Dictionary methods that are not in place#
# let's remember what is stored in the car dictionary:
car
# Return the keys in the dictionary
out = car.keys()
print(out)
# print keys
print(type(out))
print(out)
# car has not changed
print(type(car))
print(car)
# Return the values in the dicionary
car.values()
Finding Methods#
Typing the object/variable name you want to find methods for followed by a ‘.’ and then pressing tab will display all the methods available for that type of object.
# Define a test string
my_string = 'Python'
# See all the available methods on an object with tab complete
my_uppercase_string = my_string.
print(my_string)
print(my_uppercase_string)
Using the function dir()
returns all methods available
# For our purposes now, you can ignore any leading underscores (these are special methods)
dir(my_string)
Correspondance Between Functions & Methods#
All methods are functions. Methods are special functions attached to a variable type. All functions are NOT methods.
Note that:
my_variable.function_call()
acts like:
function_call(my_variable)
A function that we can call directly on a variable (a method) acts like a shortcut for passing that variable into a function.
Functions: Reminders#
Additional notes included here to remind you of points we’ve already discussed.
def
defines a functionfunction_name()
- parentheses are required to execute a functionfunction_name(input1)
- input parameters are specified within the function parenthesesfunction_name(input1, input2)
- functions can take multiple parameters as inputsinput1
andinput2
can then be used within your function when it executes
To store the output from a function, you’ll need a
return
statement
For example….#
If you write a function called is_odd()
which takes an input value
,
def is_odd(value):
if value % 2 != 0:
answer = True
else:
answer = False
return answer
to use that function, you would execute is_odd(value)
….something like is_odd(value = 6)
out = is_odd(6)
out
Later on, if you wanted to use that function within another function you still have to pass an input to the function.
def new_function(my_list):
output = []
for val in my_list:
if is_odd(val):
output.append('yay!')
return output
new_function([1,2,3,4])
More Functions & Methods#
sort_array
#
A version of a selection sort:
loop through current list
find lowest item
put that at the front of your sorted list
remove lowest item from current list
wash, rinse, repeat
def sort_array(array_to_sort):
"""A function to sort an array."""
is_sorted = False # Keeps track of when we are done sorting
sorted_array = [] # A new list that we will use to
while not is_sorted:
lowest = None
for item in array_to_sort:
if lowest == None: # If not defined (first element) set the current element as lowest
lowest = item
if item < lowest:
lowest = item
# these next two lines uses some new (to us) list methods
# these methods save us from having to loop through the list again
sorted_array.append(lowest) # Add the lowest value to our sorted array output
array_to_sort.remove(lowest) # Drop the now sorted value from the original array
if len(array_to_sort) == 0: # When `array_to_sort` is empty, we are done sorting
is_sorted = True
return sorted_array
Using sort_array
#
# Sort an array of integers
unsorted_array = [12, 7, 19, 12, 25]
sorted_array = sort_array(unsorted_array)
print(sorted_array)
# Sort an array of floats
unsorted_array = [21.3, 56.7, 2.3, 2.9, 99.9]
sorted_array = sort_array(unsorted_array)
print(sorted_array)
SideNote: sorted
#
# Sort a list, with `sorted`
data = [7.8, 4.2, 6.0]
sorted(data)
# what about a list of strings?
sorted(['asdf','abcd'])
# Sort different data types
print(sorted(['a', 'c', 'b']))
print(sorted([True, False, True]))
print(sorted([[1, 4], [1, 2]]))