List Exercises 3

Harold Nelson

9/24/2020

Ex1 Append and Concatenate

What is the difference between appending to a list and concatenation? To answer this question combine two lists in two different ways.

  1. Concatenate them using “+”.
  2. Combine them by appending one list to the other.

What’s the difference?

Answer

l1 = [1,2,3]
l2 = [4,5,6]

l3c = l1 + l2
print(l3c)
## [1, 2, 3, 4, 5, 6]
l1.append(l2)
print(l1)
## [1, 2, 3, [4, 5, 6]]

Using concatenation, the result (l3c) was a new list containing all of the members of the two lists.

The second list became a member of the first list when the second was appended to the first.

Ex2

Why didn’t I store the result of appending in a new list? Try and see.

Answer

l1 = [1,2,3]
l2 = [4,5,6]


l3a = l1.append(l2)
print(l3a)
## None

The method append is void. It changed l1, but it did not return a value.

Ex3

If a list contains another list, what does the len() function return? Does it add up the len() values of the component lists.

Answer

print(l1)
## [1, 2, 3, [4, 5, 6]]
print(len(l1))
## 4

The sublist only adds 1 to the length of the list.

Ex4

Write a function undup(l). The parameter l is a list. It returns an unduplicated list. In the result, there is one instance of every item in the input list.

Answer

def undup(l):
    res = []
    for item in l:
        if item not in res:
            res.append(item)
    return res
    
mylist = [1,2,3,3,4,1,5,5,5]
uml = undup(mylist)
print(uml)
            
## [1, 2, 3, 4, 5]

Ex5

Write a function numres(nl). It’s single parameter is a list of numbers. It returns a list of numbers. The first item in the output list is the count of numbers in the input. The second number is the sum. The third number is the mean.

Answer

def numres(nl):
    sum = 0
    for n in nl:
        sum = sum + n
    mean =  sum/len(nl)
    return [len(nl),sum, mean]
    
my_list = [1,2,3,4,5]
print(numres(my_list))
## [5, 15, 3.0]

Ex6

Create a list xlist. The first item in the list is the number 1. The second item in the list is a list [“a”,“b”,[“x”,“y”]]. Print your list to make sure it’s OK.

xlist = [1,["a","b",["x","y"]]]
print(xlist)
## [1, ['a', 'b', ['x', 'y']]]

Ex7

Write code which gets the number 1 from this list and prints it.

Answer

print(xlist)
## [1, ['a', 'b', ['x', 'y']]]
print(xlist[0])
## 1

Ex8

Write code which gets the letter ‘b’ from this list and prints it.

Answer

print(xlist)
## [1, ['a', 'b', ['x', 'y']]]
print(xlist[1][1])
## b

Ex9

Write code which gets the letter ‘y’ from this list and prints it.

Answer

print(xlist)
## [1, ['a', 'b', ['x', 'y']]]
print(xlist[1][2][1])
## y