Lists and Functions

I Lists

i. List accessing 1/18

n = [1, 3, 5]
print n[1]

ii. List element modification 2/18

n = [1, 3, 5]
n[1] = n[1]*5
print n

iii. Appending to a list 3/18

n = [1, 3, 5]
n.append(4)
print n

iv. Removing elements from lists 4/18

n = [1, 3, 5]
n.remove(1)
print n

II Function Recap

i. Changing the functionality of a function 5/18

number = 5

def my_function(x):
    return x * 3

print my_function(number)

ii. More than one argument 6/18

m = 5
n = 13
def add_function(x,y):
    return x + y
print add_function(m, n)

iii. Strings in functions 7/18

n = "Hello"
def string_function(s):
    return s + 'world'
print string_function(n)

III Introduction to Using Functions With Lists

i. Passing a list to a function 8/18
Save and Submit

ii Using an element from a list in a function 9/18

def list_function(x):
    return x[1]

n = [3, 5, 7]
print list_function(n)

iii. Modifying an element of a list in a function 10/18

def list_function(x):
    x[1] = x[1] + 3
    return x
n = [3, 5, 7]
list_function(n)
print n

iv. List manipulation in functions 11/18

n = [3, 5, 7]
def list_extender(lst):
    lst.append(9)
    return lst
print list_extender(n)

IV Using the Entire List in a Function

i. Printing out a list item by item in a function 12/18

n = [3, 5, 7]
def print_list(x):
    for i in range(0,len(x)):
        print x[i]
    return x
print_list(n)

ii. Modifying each element in a list in a function 13/18

n = [3, 5, 7]
def double_list(x):
    for i in range(0, len(x)):
        x[i] = x[i] * 2
    return x
print double_list(n)

iii. Passing a range into a function 14/18

def my_function(x):
    for i in range(0, len(x)):
        x[i] = x[i] * 2
    return x

print my_function(range(3))

iv. Iterating over a list in a function 15/18

n = [3, 5, 7]

def total(numbers):
    result = 0
    for i in numbers:
        result = result + i
    return result

v. Using strings in lists in functions 16/18

n = ["Michael", "Lieberman"]
def join_strings(words):
    result = ""
    for i in words:
        result = result + i
    return result

print join_strings(n)

V Using Lists of Lists in Functions

i. Using two lists as two arguments in a function 17/18

m = [1, 2, 3]
n = [4, 5, 6]

def join_lists(x,y):
    return x + y

print join_lists(m, n)

ii. Using a list of lists in a function 18/18

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
    results = []
    for numbers in lists:
        results = results + numbers
    return results
      
print flatten(n)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s