List Exercises 2

Harold Nelson

2/4/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)
## 4

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)    
## [52, 30, 49, 40, 36, 30, 1, 18, 35, 44, 27, 64, 79, 29, 17, 34, 45, 26, 84, 25]

Exercise

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

Answer

randlist.sort()
print(randlist)
## [1, 17, 18, 25, 26, 27, 29, 30, 30, 34, 35, 36, 40, 44, 45, 49, 52, 64, 79, 84]

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)
## [1, 17, 18, 25, 26, 27, 29, 30, 30, 34, 35, 36, 40, 44, 45, 49, 52, 64, 79, 84, 150]

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

Exercise

Create a function how_many_a_in_b with two parameters a and b. The parameter a is a single object of any type. The parameter b is a list. The function returns the number of times the object a is found in the list b. Test your function with a few different objects and lists.

Answer

# Create the function
def how_many_a_in_b(a,b):
    count = 0
    for item in b:
        if a == item:
            count = count + 1
    return count
 
# Create some test data    
l = list(range(5))
l = l + l + l

# Do a test
print(how_many_a_in_b(1,l))
## 3
l = list("Mary had a little lamb")
print(l)
# 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_b("a",l))
## 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_b("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.