List Exercises

About List Exercises

Pluralize All (Map)

Implement a function called pluralize_all: →

Pluralize All … Output

print(pluralize_all(["zebra", "cow", "tiger"]))
['zebras', 'cows', 'tigers']

Pluralize All Potential Solution

def pluralize_all(words):
	new_list = []
	for word in words:
		new_list.append(word + 's')
	return new_list

More Characters Than (Filter)

Implement a function called more_characters_than: →

More Characters Than Example

print(more_characters_than(["zebra", "cow", "tiger"], 4))
['zebra', 'tiger']

More Characters Than Potential Solution

def more_characters_than(words, min):
	new_list = []
	for word in words:
		if len(word) > min:
			new_list.append(word)
	return new_list

assert ['zebra', 'tiger'] == more_characters_than(["zebra", "cow", "tiger"], 4), "only strings with more than 4 characters"
assert [] == more_characters_than([], 4), "an empty list returns an empty list"

Average (Reduce)

Implementing Average

def average(numbers):
	sum = 0
	for n in numbers:
		sum += n
	return sum / len(numbers)

assert 9 == average([2, 3, 4]), "takes a list of integers and returns the average value"

Using the built-in sum:

def average(numbers):
	return sum(numbers) / len(numbers)

Notes

Interested in other ways to do this? Check out…

Lists and Mutability