6 - Methods and Functions Flashcards

1
Q

What are the methods for a List? (There are eight of them.)

A

Fortunately, with iPython and the Jupyter Notebook we can quickly see all the possible methods using the tab key. The methods for a list are:

append
count
extend
insert
pop
remove
reverse
sort

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you add elements to the end of a list?

A

Create a simple list

lst = [1,2,3,4,5]

lst.append(6)

lst
[1, 2, 3, 4, 5, 6]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you determine the number of times a specific item occurs in a List?

A

Check how many times 2 shows up in the list

Great! Now how about count()? The count() method will count the number of occurrences of an element in a list.

lst = [1, 2, 3, 4, 5, 6]

lst.count(2)

2 occurs once

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

With Python, how do you get more information on a specific method?

A

You can always use Shift+Tab in the Jupyter Notebook to get more help about the method. In general Python you can use the help() function:

help(lst.count)

Help on built-in function count:

count(…) method of builtins.list instance
L.count(value) -> integer – return number of occurrences of value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a function?

A

Formally, a function is a useful device that groups together a set of statements so they can be run more than once. They can also let us specify parameters that can serve as inputs to the functions.

On a more fundamental level, functions allow us to not have to repeatedly write the same code again and again.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why even use functions?

A

Put simply, you should use functions when you plan on using a block of code multiple times. The function will allow you to call the same block of code without having to write it multiple times. This in turn will allow you to create more complex Python scripts. To really understand this though, we should actually write our own functions!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the first keyword needed to create a function?

A

def

def name_of_function(arg1,arg2):
‘’’
This is where the function’s Document String (docstring) goes.
When you call help() on your function it will be printed out.
‘’’
# Do stuff here
# Return desired result

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you call a function?

A

Use the function name + ()

say_hello()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What happens if you try to call a function without the () ?

A

If you forget the parenthesis (), it will simply display the fact that say_hello is a function. Later on we will learn we can actually pass in functions into other functions! But for now, simply remember to call functions with ().

say_hello

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do have a function return a value?

A

Use the ‘return’ keyword.

def add_num(num1,num2):
return num1+num2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Why does this not work?

def check_even_list(num_list):
# Go through each number
for number in num_list:
# Once we get a “hit” on an even number, we return True
if number % 2 == 0:
return True
else:
return False

A

def check_even_list(num_list):
# Go through each number
for number in num_list:
# Once we get a “hit” on an even number, we return True
if number % 2 == 0:
return True
# This is WRONG! This returns False at the very first odd number!
# It doesn’t end up checking the other numbers in the list!
else:
return False

** Correct Approach: We need to initiate a return False AFTER running through the entire loop**
def check_even_list(num_list):
# Go through each number
for number in num_list:
# Once we get a “hit” on an even number, we return True
if number % 2 == 0:
return True
# Don’t do anything if its not even
else:
pass
# Notice the indentation! This ensures we run through the entire for loop
return False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you unpack Tuples?

A

stock_prices = [(‘AAPL’, 200),(‘GOOG’, 300),(‘MSFT’, 400)]

for stock,price in stock_prices:
print(price)

200
300
400

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does the map() function do?

A

To get the results, either iterate through map()

def square(num):
return num**2

my_nums = [1,2,3,4,5]

# or just cast to a list
list(map(square, my_nums))

[1, 4, 9, 16, 25]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the filter() function?

A

The filter function returns an iterator yielding those items of iterable for which function(item) is true. Meaning you need to filter by a function that returns either True or False. Then passing that into filter (along with your iterable) and you will get back only the results that would return True when passed to the function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does the filter() look like?

A

def check_even(num):
return num % 2 == 0

nums = [0,1,2,3,4,5,6,7,8,9,10]

list(filter(check_even,nums))

[0, 2, 4, 6, 8, 10]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What does the lambda expression do?

A

One of Pythons most useful (and for beginners, confusing) tools is the lambda expression. lambda expressions allow us to create “anonymous” functions. This basically means we can quickly make ad-hoc functions without needing to properly define a function using def.

17
Q

What are the differences between a lambda function and a regular def function?

A

Function objects returned by running lambda expressions work exactly the same as those created and assigned by defs. There is key difference that makes lambda useful in specialized roles:

lambda’s body is a single expression, not a block of statements.

The lambda’s body is similar to what we would put in a def body’s return statement. We simply type the result as an expression instead of explicitly returning it. Because it is limited to an expression, a lambda is less general that a def. We can only squeeze design, to limit program nesting. lambda is designed for coding simple functions, and def handles the larger tasks.

18
Q

What does a lambda function that squares a number look like?

A

lambda num: num ** 2

or

square = lambda num: num **2
square(2)
4

19
Q

What does a lambda expression that reverses a string look like”

A

lambda s: s[::-1]

20
Q

What does a simple lambda function with two arguments look like?

A

lambda x, y : x + y

21
Q

What is the result of this code?

x = 25

def printer():
x = 50
return x

print(x)
print(printer())

A

print(x)
25

print(printer(x))
50

22
Q

What is scope?

A

Interesting! But how does Python know which x you’re referring to in your code? This is where the idea of scope comes in. Python has a set of rules it follows to decide what variables (such as x in this case) you are referencing in your code. Lets break down the rules:

This idea of scope in your code is very important to understand in order to properly assign and call variable names.

In simple terms, the idea of scope can be described by 3 general rules:

  1. Name assignments will create or change local names by default.
  2. Name references search (at most) four scopes, these are:

local
enclosing functions
global
built-in

  1. Names declared in global and nonlocal statements map assigned names to enclosing module and function scopes.

The statement in #2 above can be defined by the LEGB rule.

LEGB Rule:

L: Local — Names assigned in any way within a function (def or lambda), and not declared global in that function.

E: Enclosing function locals — Names in the local scope of any and all enclosing functions (def or lambda), from inner to outer.

G: Global (module) — Names assigned at the top-level of a module file, or declared global in a def within the file.

B: Built-in (Python) — Names preassigned in the built-in names module : open, range, SyntaxError,…

23
Q

What is the ‘global’ keyword?

A

If you want to assign a value to a name defined at the top level of the program (i.e. not inside any kind of scope such as functions or classes), then you have to tell Python that the name is not local, but it is global. We do this using the global statement. It is impossible to assign a value to a variable defined outside a function without the global statement.

The global statement is used to declare that x is a global variable - hence, when we assign a value to x inside the function, that change is reflected when we use the value of x in the main block.

The ‘global’ keyword allows you to change the global variable inside a function.

x = 50

def func():
global x
print(‘This function is now using the global x!’)
print(‘Because of global x is: ‘, x)
x = 2
print(‘Ran func(), changed global x to’, x)

print(‘Before calling func(), x is: ‘, x)
func()
print(‘Value of x (outside of func()) is: ‘, x)

Before calling func(), x is: 50
This function is now using the global x!
Because of global x is: 50
Ran func(), changed global x to 2
Value of x (outside of func()) is: 2

24
Q

The ‘ *args ‘ argument does what?

A

When a function parameter starts with an asterisk, it allows for an arbitrary number of arguments, and the function takes them in as a tuple of values. Rewriting the above function:

It’s the asterisks that are key.

def myfunc(args):
return sum(args)
.05

myfunc(40,60,20)

6.0

25
Q

The ‘ **kwargs ‘ argument does what?

A

Python offers a way to handle arbitrary numbers of keyworded arguments. Instead of creating a tuple of values, **kwargs builds a dictionary of key/value pairs.

def myfunc(**kwargs):
if ‘fruit’ in kwargs:
print(f”My favorite fruit is {kwargs[‘fruit’]}”) # review String Formatting and f-strings if this syntax is unfamiliar
else:
print(“I don’t like fruit”)

myfunc(fruit=’pineapple’)
My favorite fruit is pineapple

myfunc()
I don’t like fruit

26
Q

Can you use *args and **kwargs in the same function?

A

Yes.

27
Q

If you use *args and **kwargs in the same function, which comes first?

A

You can pass *args and **kwargs into the same function, but *args have to appear before **kwargs