Lists and Loops Answers¶
List Exercises¶
Combined Lists¶
Make a function that takes two lists and returns a new list containing all elements from both lists. It should work like this:
>>> first = [1, 2, 3]
>>> second = [4, 5, 6]
>>> combine_lists(first, second)
[1, 2, 3, 4, 5, 6]
Answers
Idiomatic:
def combine_lists(one, two):
return one + two
Longer:
def combine_lists(one, two):
new_list = []
new_list += one
new_list += two
return new_list
Using Methods:
def combine_lists(one, two):
new_list = []
new_list.extend(one)
new_list.extend(two)
return new_list
Remove first item¶
Remove the first item from a list.
Answers
>>> my_list = [1, 2, 3, 4, 5, 6]
>>> my_list.pop(0)
1
Remove last item¶
Remove the last item from a list.
Answers
>>> my_list = [1, 2, 3, 4, 5, 6]
>>> my_list.pop()
6
Remove item by value¶
Make the following list:
>>> names = ["Alice", "Bob", "Christy", "Jules"]
Remove “Bob” from our list without referencing its index number.
Answers
>>> names = ["Alice", "Bob", "Christy", "Jules"]
>>> names.remove('Bob')
>>> names
['Alice', 'Christy', 'Jules']
Join Words¶
Create a list of words:
>>> words = ["these", "are", "some", "words"]
In one line of code, print all words in the list to the terminal, separating them each by a line break.
Answers
>>> words = ["these", "are", "some", "words"]
>>> print("\n".join(words))
these
are
some
words
Slice Exercises¶
Last N Elements¶
Write a function that returns the last items of a list
- Make a list with 5 of your favorite fruits
- Write a slice that gets the last 3 fruits
Answers
def last_n(sequence, n):
return sequence[-n:]
Last N words¶
- Create a string containing the
declaration of independence - Get a list of the last 6 words from the declaration of independence
- Get a string of the last 31 words from the declaration of independence
Answers
>>> declaration = """Action of Second Continental Congress,
... July 4, 1776.
... The unanimous Declaration of the thirteen united States of America,
... WHEN in the Course of human Events, it becomes necessary for one People to dissolve the Political Bands which have connected them with another, and to assume among the Powers of the Earth, the separate and equal Station to which the Laws of Nature and of Nature’s God entitle them, a decent Respect to the Opinions of Mankind requires that they should declare the causes which impel them to the Separation.
...
... WE hold these Truths to be self-evident, that all Men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty, and the Pursuit of Happiness—That to secure these Rights, Governments are instituted among Men, deriving their just Powers from the Consent of the Governed, that whenever any form of Government becomes destructive of these Ends, it is the Right of the People to alter or to abolish it, and to institute new Government, laying its Foundation on such Principles, and organizing its Powers in such form, as to them shall seem most likely to effect their Safety and Happiness. Prudence, indeed, will dictate that Governments long established should not be changed for light and transient Causes; and accordingly all Experience hath shewn, that Mankind are more disposed to suffer, while Evils are sufferable, than to right themselves by abolishing the forms to which they are accustomed. But when a long Train of Abuses and Usurpations, pursuing invariably the same Object, evinces a Design to reduce them under absolute Despotism, it is their Right, it is their Duty, to throw off such Government, and to provide new Guards for their future Security. Such has been the patient Sufferance of these Colonies; and such is now the Necessity which constrains them to alter their former Systems of Government. The History of the present King of Great-Britain is a History of repeated Injuries and Usurpations, all having in direct Object the Establishment of an absolute Tyranny over these States. To prove this, let Facts be submitted to a candid World.
...
... He has refused his Assent to Laws, the most wholesome and necessary for the public Good.
...
... He has forbidden his Governors to pass Laws of immediate and pressing Importance, unless suspended in their Operation till his Assent should be obtained; and when so suspended, he has utterly neglected to attend to them.
...
... He has refused to pass other Laws for the Accommodation of large Districts of People, unless those People would relinquish the Right of Representation in the Legislature, a Right inestimable to them, and formidable to Tyrants only.
...
... He has called together Legislative Bodies at Places unusual, uncomfortable, and distant from the Depository of their public Records, for the sole Purpose of fatiguing them into Compliance with his Measures.
...
... He has dissolved Representative Houses repeatedly, for opposing with manly Firmness his Invasions on the Rights of the People.
...
... He has refused for a long Time, after such Dissolutions, to cause others to be elected; whereby the Legislative Powers, incapable of Annihilation, have returned to the People at large for their exercise; the State remaining in the mean time exposed to all the Dangers of Invasion from without, and Convulsions within.
...
... He has endeavoured to prevent the Population of these States; for that Purpose obstructing the Laws for Naturalization of foreigners; refusing to pass others to encourage their Migrations hither, and raising the Conditions of new Appropriations of Lands.
...
... He has obstructed the Administration of Justice, by refusing his assent to Laws for establishing Judiciary Powers.
...
... He has made Judges dependent on his Will alone, for the Tenure of their Offices, and the Amount and Payment of their Salaries.
...
... He has erected a Multitude of new Offices, and sent hither Swarms of Officers to harrass our People, and eat out their Substance.
...
... He has kept among us, in Times of Peace, Standing Armies, without the consent of our Legislatures.
...
... He has affected to render the Military independent of and superior to the Civil Power.
...
... He has combined with others to subject us to a Jurisdiction foreign to our Constitution, and unacknowledged by our Laws; giving his Assent to their Acts of pretended Legislation:
...
... For quartering large Bodies of Armed Troops among us:
...
... For protecting them, by a mock Trial, from Punishment for any Murders which they should commit on the Inhabitants of these States:
...
... For cutting off our Trade with all Parts of the World:
...
... For imposing Taxes on us without our Consent:
...
... For depriving us, in many Cases, of the Benefits of Trial by Jury:
...
... For transporting us beyond Seas to be tried for pre-tended Offences:
...
... For abolishing the free System of English Laws in a neighbouring Province, establishing therein an arbitrary Government and enlarging its Boundaries, so as to render it at once an Example and fit Instrument for introducing the same absolute Rule into these Colonies:
...
... For taking away our Charters, abolishing our most valuable Laws, and altering fundamentally the forms of our Governments:
...
... For suspending our own Legislatures, and declaring themselves invested with Power to legislate for us in all Cases whatsoever.
...
... He has abdicated Government here, by declaring us out of his Protection and waging War against us.
...
... He has plundered our Seas, ravaged our Coasts, burnt our Towns, and destroyed the Lives of our People.
...
... He is, at this Time, transporting large Armies of foreign Mercenaries to compleat the Works of Death, Desolation, and Tyranny already begun with circumstances of Cruelty and Perfidy, scarcely paralleled in the most barbarous Ages, and totally unworthy of the Head of a civilized Nation.
...
... He has constrained our fellow Citizens taken Captive on the high Seas to bear Arms against their Country, to become the Executioners of their friends and Brethren, or to fall themselves by their Hands.
...
... He has excited domestic Insurrections amongst us, and has endeavoured to bring on the Inhabitants of our Frontiers, the merciless Indian Savages, whose known Rule of Warfare, is an undistinguished Destruction, of all Ages, Sexes and Conditions.
...
... In every stage of these Oppressions we have Petitioned for Redress in the most humble Terms: Our repeated Petitions have been answered only by repeated Injury. A Prince, whose Character is thus marked by every act which may define a Tyrant, is unfit to be the Ruler of a free People.
...
... Nor have we been wanting in Attentions to our British Brethren. We have warned them from Time to Time of Attempts by their Legislature to extend an unwarrantable jurisdiction over us. We have reminded them of the Circumstances of our Emigration and Settlement here. We have appealed to their native justice and Magnanimity, and we have conjured them by the Ties of our common Kindred to disavow these Usurpations, which, would inevitably interrupt our Connections and Correspondence. They too have been deaf to the Voice of Justice and of Consanguinity. We must, therefore, acquiesce in the Necessity, which denounces our Separation, and hold them, as we hold the rest of Mankind, Enemies in War, in Peace, Friends.
...
... We, therefore, the Representatives of the UNITED STATES OF AMERICA, in General Congress, Assembled, appealing to the Supreme Judge of the World for the Rectitude of our Intentions, do, in the Name, and by Authority of the good People of these Colonies, solemnly Publish and Declare, That these United Colonies are, and of Right ought to be, FREE AND INDEPENDENT STATES, that they are absolved from all Allegiance to the British Crown, and that all political Connection between them and the State of Great-Britain, is and ought to be totally dissolved; and that as FREE AND INDEPENDENT STATES, they have full Power to levy War, conclude Peace, contract Alliances, establish Commerce, and to do all other Acts and Things which INDEPENDENT STATES may of right do. And for the support of this Declaration, with a firm Reliance on the Protection of divine Providence, we mutually pledge to each other our Lives, our fortunes, and our sacred Honor.
... """
>>> declaration.split()[-6:]
['our', 'fortunes,', 'and', 'our', 'sacred', 'Honor.']
>>> ' '.join(declaration.split()[-31:])
'And for the support of this Declaration, with a firm Reliance on the Protection of divine Providence, we mutually pledge to each other our Lives, our fortunes, and our sacred Honor.'
Last Words¶
Create a function that takes a string as an argument and will return a new string containing the last two words of the given string, separated by a space.
It should work like this:
>>> last_two(declaration_of_independence)
'sacred Honor.'
>>> last_two("hello world")
'hello world'
>>> last_two("hi")
'hi'
Answers
def last_two(string):
return " ".join(string.split()[-2:])
Half¶
Make a function that splits a list in half and returns both halves. It should work like this:
>>> split_in_half([1, 2, 3, 4])
([1, 2], [3, 4])
>>> split_in_half([1, 2, 3, 4, 5])
([1, 2], [3, 4, 5])
>>> split_in_half([1, 2])
([1], [2])
>>> split_in_half([])
([], [])
>>> split_in_half([1])
([], [1])
Try your function on other iterables (strings or tuples). Does it still work?
>>> split_in_half("Hello world!")
('Hello ', 'world!')
>>> split_in_half((1, 2))
((1,), (2,))
Answers
One Line:
def split_in_half(things):
return (things[:len(things) // 2], things[len(things) // 2:])
With Variable:
def split_in_half(things):
half_way = len(things) // 2
return things[:half_way], things[half_way:]
Tuple Exercises¶
Oldest¶
Make function get_oldest that accepts two dates in MM/DD/YYYY format and returns the date that is earliest.
>>> get_oldest("01/27/1832", "01/27/1756")
'01/27/1756'
>>> get_oldest("02/29/1972", "12/21/1946")
'12/21/1946'
>>> get_oldest("03/24/1946", "02/21/1946")
'02/21/1946'
Answers
With tuple unpacking and if statement:
def get_oldest(date1, date2):
(m1, d1, y1) = date1.split('/')
(m2, d2, y2) = date2.split('/')
if (y1, m1, d1) < (m2, d2, y2):
return date1
else:
return date2
With inline if:
def get_oldest(date1, date2):
(m1, d1, y1) = date1.split('/')
(m2, d2, y2) = date2.split('/')
return date1 if (y1, m1, d1) < (m2, d2, y2) else date2
Sort Names¶
The built-in sorted function accepts a key argument that determines how values should be sorted in a given iterable.
Let’s use this function to sort a list of names. Names should be sorted by last name followed by first name (when the last names are equal).
Write a function name_key that accepts a first-last name tuple and returns a last-first name tuple:
>>> suzanne = ("Suzanne", "Smith")
>>> michael = ("Michael", "Gambino")
>>> name_key(michael)
('Gambino', 'Michael')
>>> name_key(suzanne)
('Smith', 'Suzanne')
Now write a function sort_names that accepts a list of first-last name tuples and returns a sorted list (using sorted with key).
>>> evelyn = ("Evelyn", "Moore")
>>> jill = ("Jill", "Moore")
>>> tanya = ("Tanya", "Jackson")
>>> ben = ("Ben", "Speigel")
>>> names = [tanya, evelyn, jill]
>>> sort_names(names)
[('Tanya', 'Jackson'), ('Evelyn', 'Moore'), ('Jill', 'Moore')]
Answers
def name_key(name):
first, last = name
return last, first
def sort_names(names):
return sorted(names, key=name_key)
Loop Exercises¶
Starting with a vowel¶
Make a function that accepts a list of names and returns a new list containing all names that start with a vowel. It should work like this:
>>> names = ["Alice", "Bob", "Christy", "Jules"]
>>> vowel_names(names)
['Alice']
>>> names = ["Scott", "Arthur", "Jan", "Elizabeth"]
>>> vowel_names(names)
['Arthur', 'Elizabeth']
Answers
def vowel_names(names):
new_list = []
for name in names:
if name[0].lower() in 'aeiou':
new_list.append(name)
return new_list
Average¶
Make a program average.py that calculates the average of all given command-line arguments and prints a message “No numbers to average!” if there are no arguments given:
$ python average.py
No numbers to average!
$ python average.py 2 3 4 5 6 7
Average is 4.5
$ python average.py 2 3 4
Average is 3.0
Answers
import sys
arguments = sys.argv[1:]
if __name__ == "__main__":
if arguments:
total = 0
for num in arguments:
total += float(num)
print("Average is {}".format(total/len(arguments)))
else:
print("No numbers to average!")
Later we will see better ways to do this.
Bonus: X marks the spot¶
- Create a string containing the declaration of independence
- Print all words in the declaration of independence that contain the letter “x”
Answers
>>> for word in declaration.split():
... if 'x' in word.lower():
... print(word)
...
Experience
exercise;
exposed
Taxes
Example
Executioners
excited
Sexes
extend
Bonus: Secret Message¶
- Create a string containing the
declaration of independence - Get a list of all uppercase letters in the declaration of independence
- Find a secret 4 letter word in this uppercase letter list. The word starts at index 374 ends at index 382, and skips every other letter
Answers
>>> for letter in declaration:
... if letter.isupper():
... uppers.append(letter)
...
>>> uppers
['A', 'S', 'C', 'C', 'J', 'T', 'D', 'S', 'A', 'W', 'H', 'E', 'N', 'C', 'E', 'P', 'P', 'B', 'P', 'E', 'S', 'L', 'N', 'N', 'G', 'R', 'O', 'M', 'S', 'W', 'E', 'T', 'M', 'C', 'R', 'L', 'L', 'P', 'H', 'T', 'R', 'G', 'M', 'P', 'C', 'G', 'G', 'E', 'R', 'P', 'G', 'F', 'P', 'P', 'S', 'H', 'P', 'G', 'C', 'E', 'M', 'E', 'B', 'T', 'A', 'U', 'O', 'D', 'D', 'R', 'D', 'G', 'G', 'S', 'S', 'S', 'C', 'N', 'S', 'G', 'T', 'H', 'K', 'G', 'B', 'H', 'I', 'U', 'O', 'E', 'T', 'S', 'T', 'F', 'W', 'H', 'A', 'L', 'G', 'H', 'G', 'L', 'I', 'O', 'A', 'H', 'L', 'A', 'D', 'P', 'P', 'R', 'R', 'L', 'R', 'T', 'H', 'L', 'B', 'P', 'D', 'R', 'P', 'C', 'M', 'H', 'R', 'H', 'F', 'I', 'R', 'P', 'H', 'T', 'D', 'L', 'P', 'A', 'P', 'S', 'D', 'I', 'C', 'H', 'P', 'S', 'P', 'L', 'N', 'M', 'C', 'A', 'L', 'H', 'A', 'J', 'L', 'J', 'P', 'H', 'J', 'W', 'T', 'O', 'A', 'P', 'S', 'H', 'M', 'O', 'S', 'O', 'P', 'S', 'H', 'T', 'P', 'S', 'A', 'L', 'H', 'M', 'C', 'P', 'H', 'J', 'C', 'L', 'A', 'A', 'L', 'F', 'B', 'A', 'T', 'F', 'T', 'P', 'M', 'I', 'S', 'F', 'T', 'P', 'W', 'F', 'T', 'C', 'F', 'C', 'B', 'T', 'J', 'F', 'S', 'O', 'F', 'S', 'E', 'L', 'P', 'G', 'B', 'E', 'I', 'R', 'C', 'F', 'C', 'L', 'G', 'F', 'L', 'P', 'C', 'H', 'G', 'P', 'W', 'H', 'S', 'C', 'T', 'L', 'P', 'H', 'T', 'A', 'M', 'W', 'D', 'D', 'T', 'C', 'P', 'A', 'H', 'N', 'H', 'C', 'C', 'S', 'A', 'C', 'E', 'B', 'H', 'H', 'I', 'I', 'F', 'I', 'S', 'R', 'W', 'D', 'A', 'S', 'C', 'I', 'O', 'P', 'R', 'T', 'O', 'P', 'I', 'A', 'P', 'C', 'T', 'R', 'P', 'N', 'A', 'B', 'B', 'W', 'T', 'T', 'A', 'L', 'W', 'C', 'E', 'S', 'W', 'M', 'T', 'K', 'U', 'C', 'C', 'T', 'V', 'J', 'C', 'W', 'N', 'S', 'M', 'E', 'W', 'P', 'F', 'W', 'R', 'U', 'N', 'I', 'T', 'E', 'D', 'S', 'T', 'A', 'T', 'E', 'S', 'O', 'F', 'A', 'M', 'E', 'R', 'I', 'C', 'A', 'G', 'C', 'A', 'S', 'J', 'W', 'R', 'I', 'N', 'A', 'P', 'C', 'P', 'D', 'T', 'U', 'C', 'R', 'F', 'R', 'E', 'E', 'A', 'N', 'D', 'I', 'N', 'D', 'E', 'P', 'E', 'N', 'D', 'E', 'N', 'T', 'S', 'T', 'A', 'T', 'E', 'S', 'A', 'B', 'C', 'C', 'S', 'G', 'B', 'F', 'R', 'E', 'E', 'A', 'N', 'D', 'I', 'N', 'D', 'E', 'P', 'E', 'N', 'D', 'E', 'N', 'T', 'S', 'T', 'A', 'T', 'E', 'S', 'P', 'W', 'P', 'A', 'C', 'A', 'T', 'I', 'N', 'D', 'E', 'P', 'E', 'N', 'D', 'E', 'N', 'T', 'S', 'T', 'A', 'T', 'E', 'S', 'A', 'D', 'R', 'P', 'P', 'L', 'H']
>>> "".join(uppers[374 : 382 : 2])
'NEED'
Range Exercises¶
Power By Index¶
Make a function, ith_item_power, that accepts a list of numbers and an index number and returns the i-th element raised to the i-th power where i is the given index number. For example:
>>> ith_item_power([3, 2, 5], 2)
25
>>> ith_item_power([5, 6, 2, 7, 3], 4)
81
Answers
def ith_item_power(nums, power):
return nums[power] ** power
Power List By Index¶
Make a function, power_list, that accepts a list and returns a new list that contains each number raised to the i-th power where i is the index of that number in the given list. For example:
>>> power_list([3, 2, 5])
[1, 2, 25]
>>> numbers = [78, 700, 82, 16, 2, 3, 9.5]
>>> power_list(numbers)
[1, 700, 6724, 4096, 16, 243, 735091.890625]
Answers
With enumerate (most idiomatic):
def power_list(numbers):
powers = []
for i, number in enumerate(numbers):
powers.append(number ** i)
return powers
With range:
def power_list(nums):
new_list = []
for i in range(len(nums)):
new_list.append(nums[i] ** i)
return new_list
Divisible¶
Make a list of all numbers between 100 and 300 that are divisible by both 6 and 10.
Answers
With and:
>>> divisible = []
>>> for i in range(301):
... if i % 6 == 0 and i % 10 == 0:
... divisible.append(i)
...
>>> divisible
[30, 60, 90, 120, 150, 180, 210, 240, 270, 300]
With step:
>>> divisible = []
>>> for i in range(6, 301, 6):
... if i % 10 == 0:
... divisible.append(i)
...
>>> divisible
[30, 60, 90, 120, 150, 180, 210, 240, 270, 300]
99 Bottles¶
Write a program called bottles.py that when executed will print the lyrics to the song “99 bottles of beer”. Feel free to substitute your favorite beverage in place of beer.
The song has 100 verses. Each verse is structured like this:
99 bottles of milk on the wall, 99 bottles of milk.
Take one down, pass it around, 98 bottles of milk on the wall...
This same verse is repeated, each time with one less bottle. So the second verse is:
98 bottles of milk on the wall, 98 bottles of milk.
Take one down, pass it around, 97 bottles of milk on the wall...
The last verse does not use numbers. The last two verses are:
1 bottle of milk on the wall, 1 bottle of milk.
Take one down, pass it around, no more bottles of milk on the wall...
No more bottles of milk on the wall, no more bottles of milk.
Go to the store and buy some more, 99 bottles of milk on the wall...
Answers
for num in range(99, 0, -1):
if num > 1:
bottle = "bottles"
num_left = num - 1
if num > 2:
next_bottle = "bottles"
else:
next_bottle = "bottle"
else:
bottle = "bottle"
num_left = "no more"
next_bottle = "bottles"
print("{num} {bottle} of milk on the wall, {num} {bottle} of milk."
.format(num=num, bottle=bottle))
print("Take one down, pass it around, "
"{num} {bottle} of milk on the wall..."
.format(num=num_left, bottle=next_bottle))
print("No more bottles of milk on the wall, no more bottles of milk.")
print("Go to the store and buy some more, 99 bottles of milk on the wall...")