List Exercises 3

Harold Nelson

2/4/2020

Ex1 Append and Concatenate

What is the difference between appending to a list and concatenation?

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]]

The second list became a member of the first list.

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]

l3c = l1 + l2
print(l3c)
## [1, 2, 3, 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 prints each of the following items.

  1. The number 1
  2. The letter ‘b’
  3. The letter ‘y’

Answer

print(xlist[0])
## 1
print(xlist[1][1])
## b
print(xlist[1][2][1])
## y