List Exercises 2

Harold Nelson

9/24/2020

Exercise

Google for help on the randint() function and use it to get and print a single random integer between 0 and 100.

Answer

import random
x = random.randint(0,100)
print(x)
## 3

Exercise

Use randint() to create a list of 20 random integers between 0 and 100.

Answer

randlist = []
for i in range(20):
    randlist.append(random.randint(0,100))
print(randlist)    
## [8, 8, 83, 95, 69, 52, 87, 76, 27, 0, 98, 10, 59, 32, 95, 70, 78, 81, 40, 47]

Exercise

Sort and print the list you created in the last problem.

Answer

randlist.sort()
print(randlist)
## [0, 8, 8, 10, 27, 32, 40, 47, 52, 59, 69, 70, 76, 78, 81, 83, 87, 95, 95, 98]

Exercise

What happens if you use the sort() method on the right side of an assignment statement?

Answer

sorted_list = randlist.sort()
print(sorted_list)
## None

Note that the sort method is void. It doesn’t return anything. What about append?

Answer

bigger = randlist.append(150)
print(bigger)
## None
print(randlist)
## [0, 8, 8, 10, 27, 32, 40, 47, 52, 59, 69, 70, 76, 78, 81, 83, 87, 95, 95, 98, 150]

Note that bigger was not produced, but the append did modify randlist.

Exercise

Create a function how_many_a_in_li with two parameters a and li. The parameter a is a single object of any type. The parameter li is a list. The function returns the number of times the object a is found in the list li. Test your function by creating a list with three copies of range(5). Verify that the number 1 occurs three times in this list.

Answer

# Create the function
def how_many_a_in_li(a,li):
    count = 0
    for item in li:
        if a == item:
            count = count + 1
    return count

# Create the test data    
li = list(range(5))
l3 = li + li + li

# Do the test
print(how_many_a_in_li(1,l3))
## 3

Exercise

Test the function again using the line “Mary had a little lamb”. Count the number of times the letter ‘a’ appeared in this line.

Answer

lpoem = list("Mary had a little lamb")
print(lpoem)
# Do another test
## ['M', 'a', 'r', 'y', ' ', 'h', 'a', 'd', ' ', 'a', ' ', 'l', 'i', 't', 't', 'l', 'e', ' ', 'l', 'a', 'm', 'b']
print(how_many_a_in_li("a",lpoem))
## 4

Exercise

Was it necessary to convert the string to a list in the previous exercise?

Answer

s = "Mary had a little lamb"
print(how_many_a_in_li("a",s))
## 4

No. I wrote the function thinking of b as a list, but the only restrictions on argument types are imposed by the usage of the parameter within the body of the function.